title: Single page application with HttpOnly cookie-based authentication and session management
body: <p>For several days now I've been looking for a secure authentication and session management mechanism for my single page application. Judging by the numerous tutorials and blog posts out there about SPAs and authentication, storing JWTs in localStorage or regular cookies seems to be the most common approach, but <a href="http://cryto.net/~joepie91/blog/2016/06/13/stop-using-jwt-for-sessions/" rel="noreferrer">it's simply not a good idea to use JWTs for sessions</a> so it's not an option for this app.</p>
  
  <p><strong>Requirements</strong></p>
  
  <ul>
  <li>Logins should be revokable. For example, if suspicious activity is detected on a user's account, it should be possible to revoke that user's access immediately and require a new log in. Similarly, things like password resets should revoke all existing logins.</li>
  <li>Authentication should happen over Ajax. No browser redirection ("hard" redirection) should take place afterwards. All navigation should happen inside the SPA.</li>
  <li>Everything should work cross-domain. The SPA will be on www.domain1.com and the server will be on www.domain2.com.</li>
  <li>JavaScript should have no access to sensitive data sent by the server, such as session IDs. This is to prevent XSS attacks where malicious scripts can steal the tokens or session IDs from regular cookies, localStorage or sessionStorage.</li>
  </ul>
  
  <p>The ideal mechanism seems to be cookie-based authentication using <code>HttpOnly</code> cookies that contain session IDs. The flow would work like this:</p>
  
  <ol>
  <li>User arrives at a login page and submits their username and password.</li>
  <li>The server authenticates the user and sends a session ID as an <code>HttpOnly</code> response cookie.</li>
  <li>The SPA then includes this cookie in subsequent XHR requests made to the server. This seems to be possible using the <code>withCredentials</code> option.</li>
  <li>When a request is made to a protected endpoint, the server looks for the cookie. If found, it cross-checks that session ID against a database table to make sure the session is still valid.</li>
  <li>When the user logs out, the session is deleted from the database. The next time the user arrives on the site, the SPA gets a 401/403 response (since the session has expired), then takes the user to the login screen.</li>
  </ol>
  
  <p>Because the cookie has the <code>HttpOnly</code> flag, JavaScript would not be able to read its contents, so it would be safe from attacks as long as it is transmitted over HTTPS.</p>
  
  <p><strong>Challenges</strong></p>
  
  <p>Here's the specific issue I've run into. My server is configured to handle CORS requests. After authenticating the user, it correctly sends the cookie in the response:</p>
  
  <pre><code>HTTP/1.1 200 OK
  server: Cowboy
  date: Wed, 15 Mar 2017 22:35:46 GMT
  content-length: 59
  set-cookie: _myapp_key=SFMyNTYBbQAAABBn; path=/; HttpOnly
  content-type: application/json; charset=utf-8
  cache-control: max-age=0, private, must-revalidate
  x-request-id: qi2q2rtt7mpi9u9c703tp7idmfg4qs6o
  access-control-allow-origin: http://localhost:8080
  access-control-expose-headers: 
  access-control-allow-credentials: true
  vary: Origin
  </code></pre>
  
  <p>However, the browser does not save the cookie (when I check Chrome's local cookies it's not there). So when the following code runs:</p>
  
  <pre><code>context.axios.post(LOGIN_URL, creds).then(response =&gt; {
    context.$router.push("/api/account")
  }
  </code></pre>
  
  <p>And the Account page is created:</p>
  
  <pre><code>created() {
    this.axios.get(SERVER_URL + "/api/account/", {withCredentials: true}).then(response =&gt; {
      //do stuff
    }
  }
  </code></pre>
  
  <p>This call does not have the cookie in the header. The server therefore rejects it.</p>
  
  <pre><code>GET /api/account/ HTTP/1.1
  Host: localhost:4000
  Connection: keep-alive
  Accept: application/json
  Origin: http://localhost:8080
  User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36
  Referer: http://localhost:8080/
  Accept-Encoding: gzip, deflate, sdch, br
  Accept-Language: en-US,en;q=0.8,tr;q=0.6
  </code></pre>
  
  <p>Do I need to do something special to make sure the browser saves the cookie after receiving it in the login response? Various sources I've read have said that browsers save response cookies only when the user is redirected, but I don't want any "hard" redirects since this is an SPA.</p>
  
  <p>The SPA in question is written in Vue.js, but I guess it applies to all SPAs. I'm wondering how people handle this scenario.</p>
  
  <p>Other stuff I've read on this topic:</p>
  
  <ul>
  <li><a href="https://stackoverflow.com/questions/20963273/spa-best-practices-for-authentication-and-session-management">SPA best practices for authentication and session management</a></li>
  <li><a href="https://security.stackexchange.com/questions/53359/are-httponly-cookies-submitted-via-xmlhttprequest-with-withcredentials-true">Are HTTPOnly Cookies submitted via XmlHTTPRequest with withCredentials=True?</a></li>
  <li><a href="http://cryto.net/~joepie91/blog/2016/06/19/stop-using-jwt-for-sessions-part-2-why-your-solution-doesnt-work/" rel="noreferrer">Stop using JWT for sessions, part 2: Why your solution doesn't work</a></li>
  </ul>