Advanced Authentication in SPA

Cookies, sessions, tokens, JWT, where to store tokens, authentication concerns in a Single-Page Application system... everything you need to know is here.

Cookies, sessions, tokens, JWT, where to store tokens, authentication concerns in a Single-Page Application system… everything you need to know is here.

TL;DR;

You can implement Authentication in a single page application (SPA) with many models, each with its own pros and cons. This post covers the important concepts you need to know when dealing with user authentication, especially in the fairly common SPA architecture today:

SPA

Security prerequisites

Encrypt the protocol (HTTPS)

  • Authentication uses HTTP headers to carry credentials (sensitive data like passwords, access tokens, …). These connections must be encrypted, otherwise if hackers get into a user’s WiFi network, this information can be stolen.

Don’t use URL query params for sensitive data

  • URLs and URL params (e.g. http://example.com/?password=123456) can be logged on the server and stored in the browser (in history) -> they can be stolen and abused.
  • If you put the auth token in a URL query param, plenty of naive users may copy the URL from the browser and send it straight to a “hacker”. 😐
  • URL length is usually limited by the browser or server, so the integrity of the data sent can’t be guaranteed.

Prevent “brute-force” attacks

  • “Brute-force” is a trial-and-error attack, e.g. a hacker tries a huge list of passwords until one works (usually done with a tool).
  • You can prevent it by implementing a “rate limit” middleware on the backend. Almost every language / web framework today supports this.
  • Block the IP of a user who keeps probing your server for vulnerabilities (such a user usually generates lots of HTTP 3xx, 4xx and 5xx errors). Just block them to avoid trouble later 😂.
  • Don’t let people know what you run on the backend (it makes finding vulnerabilities easier 😄). Usually, remove the X-Powered-By header from responses (especially since .NET and Java frameworks often ship with it).

Update dependencies in your code regularly

  • Update the dependencies, libraries or frameworks you use regularly. Updates usually fix security vulnerabilities that have been found.
  • Here’s how to check and update dependencies if you use NodeJS (both server-side and client-side):
# Show the list of outdated libs
npm audit
# Update minor and patch versions in package.json
yarn outdated
yarn update
# Update dependencies by minor and patch in package.json
yarn upgrade-interactive
# Update to the latest version
yarn upgrade-interactive --latest
# Similar if you use NPM
npm outdated
npm update
# You can use this tool for a more thorough check: npm-check-updates
npm install -g npm-check-updates
ncu
  • Also, update the OS on your server regularly (to the latest LTS), if you aren’t using a PaaS (like Google App Engine or Heroku).

Monitor your server regularly

  • Set up monitoring and logging on the server so you can spot unusual changes before an incident happens.

Authentication mechanisms

There are 2 main authentication mechanisms (we’ll compare their pros and cons later) for authenticating users in a REST API system.

  • Bearer Token
  • Authentication cookie

Bearer Token

What is a Bearer Token?

  • A bearer token is a value in the Authorization header of each HTTP request. By default it isn’t stored anywhere (unlike a cookie), you have to decide where to store it. It also has no expiry time and no associated domain (like a cookie), it’s just a string value:
GET https://www.example.com/api/users
Authorization: Bearer my_bearer_token_value

To build a stateless application, we can use JWT to implement the Bearer Token. Basically, a JWT (JSON Web Token) has 3 parts:

  • Header
  • Payload (contains a description of the user, usually the user id and their role: member or admin + the token’s expiry time)
  • Signature

JWT is a cryptographically secure open standard that defines how to pass authentication information statelessly between 2 parties as JSON. Stateless means the server doesn’t need to store the token’s state, the user information is packed right into the token. The JWT string is encoded with Base64. The signature part of the JWT is a string encrypted from the header, the payload and a secret key. Since the signature itself covers both the header and the payload, it can be used to verify the integrity of the data in transit (like an MD5 checksum).

Basically, the client receives a JWT token once it has been authenticated with a user/password (or some other method).

After a successful authentication, with the client holding the token, every subsequent request from the client attaches this token to the request header. When the server receives a request with a token, it checks whether the signature is valid. If it is, the server uses the token’s payload to get the expire time and user information (as needed).

Basic use cases

  • Sending and receiving authenticated connections between the browser and the backend server.
  • Sending and receiving authenticated connections between mobile apps, desktop apps and the backend server.
  • Sending and receiving authenticated connections between servers (M2M) of different organizations (OpenId Connect is an example).

Where to store the JWT?

Again, JWTs (and bearer tokens in general) aren’t automatically stored on the client (browser, app). We have to implement where to store it ourselves (RAM, local/session storage, cookie, etc…).

Storing the JWT in the browser’s local storage is not recommended:

  • When the user closes the browser, the JWT is still there and can be used next time until it expires.
  • Any JavaScript on your page can access local storage: nothing protects it.
  • It can be used by a web worker.

Storing the JWT token in a session cookie can be a good solution, we’ll talk about that later.

See more details about store token in the auth0.com docs: https://auth0.com/docs/security/store-tokens

Basic attack types

  • Cross-Site Scripting (XSS) is the most basic attack you have to care about when writing JavaScript: a hacker somehow (by tampering with JS dependencies or using user input to inject malicious javascript code) steals the user’s JWT, then impersonates them.
  • For example, in a blog’s comment section, a user can add a comment containing JavaScript that does something on the page (other users will have to load this user’s JS):
<img src=x onerror="&#0000106&#0000097&#0000118&#0000097&#0000115&#0000099&#0000114&#0000105&#0000112&#0000116&#0000058&#0000097&#0000108&#0000101&#0000114&#0000116&#0000040&#0000039&#0000088&#0000083&#0000083&#0000039&#0000041">

You can prevent XSS by carefully escaping inputs (like user comments, posts) so scripting code can’t be injected. Or avoid public CDNs since they’re hard to control: if a hacker breaks in and changes the scripts on a CDN you use, your site can be attacked easily.

A cookie is a name-value pair stored in the browser, with an expiry date and an associated domain. You can create a cookie with JavaScript:

document.cookie = ‘my_cookie_name=my_cookie_value’ // JavaScript

Or from the server by returning an HTTP Response Header like this:

Set-Cookie: my_cookie_name=my_cookie_value // HTTP Response Header

The web browser automatically adds the cookie to every request to the cookie’s domain (associated domain).

GET https://www.example.com/api/users
Cookie: my_cookie_name=my_cookie_value

In most (stateful) use cases, a cookie is used to store a session ID. The session ID is managed and stored on the server (created and deleted there). Unlike a stateless JWT, a cookie session requires the server to store it.

There are 2 types of cookies (source):

  • Session cookie: the cookie only lives for one browser session. This kind of cookie has no Expires or Max-Age to indicate an expiry time. However, the browser can use session restoring to bring this cookie back even after the browser was closed, so you should handle session timeout on the server side too, just to be safe 😎.
  • Permanent cookies: instead of being deleted when the browser closes, a permanent cookie expires at a specified date (Expires) or after a specified period (Max-Age).

Also, a cookie created by the server (HTTP Response Header) can have some options:

  • HttpOnly cookie: JavaScript in the browser can never read these cookies.
  • Secure* cookie: the browser only attaches this cookie to a request when it’s made over an encrypted protocol (usually HTTPS).
  • SameSite cookie: lets the server require that a cookie not be sent with cross-site requests, which partly protects against cross-site request forgery (CSRF) attacks. SameSite is still experimental and not supported by all browsers.

Basic use cases

  • Sending and receiving authenticated connections between the browser and the backend server.
  • If the front-end is a mobile app or desktop app, authenticating with cookies is harder than with JWT.

Cookies are stored automatically by the browser, and come with an expiry time (depending on the case) and an associated domain.

Basic attack types

  • Cross-Site Scripting (XSS): same as with the JWT Bearer Token, if the cookie isn’t created with the HttpOnly option, a hacker can steal it and impersonate the user to steal information or make illegal transactions.
  • Cross-Site Request Forgery (CSRF) is a fairly common attack against cookie-authenticated sites. You can configure CORS (Cross-Origin Resource Sharing) on the server to restrict which hostnames can send requests. However, CORS is enforced on the client side by the browser. Worse, CORS can only restrict requests made from browser-side languages (JavaScript or WSM), which means if you send a request through a form (HTML Form), CORS can’t check it, like this:
<form action="http://someotherserver.com">

Because no JavaScript is involved in the request made by this form, CORS is bypassed and the cookie will be sent with the form request 😞.

Another CSRF attack example: say a user is logged in to facebook and visits a site called bad.com. This bad.com has been taken over by hackers and has a piece of code like this on the page:

<img src="https://facebook.com/postComment?userId=dupont_123&comment=I_VE_BEEN_HACKED>

To prevent CSRF, the SameSite option must be set on the cookie. However, SameSite isn’t supported by every browser yet, so it can’t stop every CSRF attack. So you need some other strategies (which can be combined):

  • Short session timeout on the server: on sites involving banking transactions, the session expiry is usually around 10 minutes or less.
  • Always ask the user to log in again for important actions: for example, when the user wants to change their email, make them re-enter their password.

Can we combine both mechanisms?

Let’s sum up what we want when implementing authentication with a server API:

  • Support client-server and server-server (M2M) authentication
  • Prevent XSS and CSRF attacks as much as possible
  • Stateless if possible (the server stores little or no state at all 😏)

The API server should support reading the JWT bearer token from the request header as well as reading the JWT token stored inside a session cookie. If we want to allow JavaScript to read the JWT payload, we can take the two cookie authentication approach by combining 2 kinds of cookies, which limits XSS attacks quite well.

Authentication-combined

You can learn about the two cookie authentication approach in this post by Peter Locke at https://medium.com/lightrail/getting-token-authentication-right-in-a-stateless-single-page-application-57d0c6474e3.

By combining the 2 mechanisms, the server can seamlessly refresh the JWT token on every request. The new token is returned through a cookie response (the server sets the cookie via the HTTP response), and the JWT is automatically stored by the browser. This way, the JWT’s expiry time can be reset on every request, giving better control, but also making the logic somewhat more complex 😕.

To limit CSRF attacks, state-changing actions (writing a comment, changing email, password, name) shouldn’t be done with an HTTP GET query, use PUT or POST instead. Important changes (email, address) should make the user log in again, just to be sure.

You can also create a temporary cookie by randomly picking a value from the cookie, putting it in the form data and submitting it with the form as a hidden form field. The server then checks that the random number in the cookie matches the value sent in the form data, and only then is the request valid.

Cookie CSRF

Summary

The authentication flow in our Single Page Application now looks like this:

  • Step 1: the SPA checks the cookie. If a JWT payload is there, it goes to the member page, otherwise it gets kicked out to the login page (/login/). If you use an httpOnly cookie, you can’t check directly with JavaScript, you have to send a request to the server to check, e.g. a request to /backend/api/me, so the server returns the user’s info or a 401 unauthorized error if the cookie (containing the JWT) is invalid.
  • Step 2 - Case 1: on the /login page, once the user finishes entering their username and password in the form, you can send them to the server to check with an AJAX request (XHR). The response to this AJAX request sets the authentication cookie with the JWT inside.
  • Step 2 - Case 2: if the /login page uses OpenID authentication via an OAuth mechanism. Following the authorization code grant flow, the /login page redirects the browser to /backend/auth/<provider>. Then, once the OAuth flow completes and is valid (the user grants login with Facebook), the server response sets the authentication cookie with the JWT inside. The browser then redirects back to the SPA page. The SPA then goes back to check as in step 1.

Reference from auth0.com, mozilla docs, jwt.io, @pdlocke, @jcbaey