Authentication in JS

JWT ( Json Web Token)

      JSON Web Tokens consist of three parts separated by dots (.), which are:

  • Header
  • Payload
  • Signature

 

Therefore, a JWT typically looks like the following.

 

xxxxx.yyyyy.zzzzz

Header

The header typically consists of two parts: the type of the token, which is JWT, and the hashing algorithm being used, such as HMAC SHA256 or RSA.

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

For example:

Payload

The second part of the token is the payload, which contains the claims. Claims are statements about an entity (typically, the user) and additional metadata. There are three types of claims: reserved, public, and privateclaims.

  • Reserved claims: These is a set of predefined claims which are not mandatory but recommended, to provide a set of useful, interoperable claims. Some of them are: iss (issuer), exp (expiration time), and others.

  • Private claims: These are the custom claims created to share information between parties that agree on using them.

{
  "sub": "1234567890",
  "name": "John Doe",
  "admin": true
}

Signature

To create the signature part you have to take the encoded header, the encoded payload, a secret, the algorithm specified in the header, and sign that.

For example if you want to use the HMAC SHA256 algorithm, the signature will be created in the following way:

HMACSHA256(
  base64UrlEncode(header) + "." +
  base64UrlEncode(payload),
  secret)

The following shows a JWT that has the previous header and payload encoded, and it is signed with a secret:

Made with Slides.com