JWT Token

Authentication and authorization are the most important security features to be implemented for any API. One way to manage this information is through sessions. Once users log in, a session is created on the server-side for the user with user metadata information. The problem with this approach is that this is stateful and difficult to scale. Another way to implement the metadata is to send back a hash or a key once the user logs in successfully, and every subsequent request needs to pass this key back. This key is stored along with user metadata is stored in the database to avoid statefulness. The disadvantage here is an additional database query, every time a request comes in.

JWT or JSON Web Token solves this problem. JWT is a string in JSON format, encrypted with a key. The encryption can be symmetric or asymmetric. JWT contains 3 sections, a header, a payload, and a signature.

Header: The header JSON normally contains two fields, a type (typ), which is always “JWT” and alg field providing algorithm used for encrypting the token.

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

Payload: This section contains JSON for any payload or data you want to send. This can contain fields that can identify the user and their roles for authorization and authentication. This can also have iat or Issued At time and token expiry time (exp).

{
"sub": "1234567890",
"name": "John Doe",
"iat": 1516239022
}

Signature: The signature is the encrypted part of the token. The encryption is done using the algorithm mentioned in the header. The signature can only be decrypted using the secret key.

Sample JWT token

Originally posted: https://cloudyforsure.com/security/jwt-token/