Authentication Using JSON Web Tokens

As the industry moves towards an API focused world simple backend based sessions won’t cut it anymore. We need a way for the client to be able to login, no matter the platform.

Cookie-based authentication has been the tried and true method of authentication for a long time.

Cookie vs Token based authentication

State vs stateless

The big difference between Traditional Cookie-Based authentication and modern Token-based authentication is whether the backend keeps a record of which users are signed in.

Token-based authentication is stateless, meaning that the backend does not keep a record of which JWTs that has been issued. Instead, the client sends its token along with the request as a header. The backend later deciphers the header containing the token and grants permission to the protected content. One common place to store the token is in the browsers local storage.
Cookie-based authentication is stateful, meaning that the session has to be kept both client and server side.

If you are building a backend that you are planning to use on multiple platforms (i.e Web, IOS, and Android apps) you should go with the token-based authentication, it’s where the industry is heading right now.

The structure of a JSON Web Token

A JSON Web Token consists of three parts separated by dots, these are:

  • Header
  • Payload
  • Signature

The header is used to tell the what hashing algorithm is used and the type of token.

{
"alg": "HS256",
"typ": "JWT"
}

The payload contains all of the data. There are some reserved claims that are highly recommended to include. Examples are: iss (issuer), sub (subject), exp (expiration date). The subject is used to tell which user the token was issued for. A common practice is to set the subject to the ID of the user.

{
"iss": "Victors monkey farm",
"sub": "jhrhuj2b423ghfhsdkf", // The user ID
"exp": 165464522485
}

Play with it here

Authentication using Node and Passport.js

This will be an example of how to use JSON Web Tokens with Node and Passport.js, I will only show how to integrate it. Not how to setup passport and your node application.

Sources