(JWT) JSON Web Tokens for API

In modern era, Authentication and authorization are used widely in mostly every app out there. While authentication establishesh user’s (or machine’s/thing’s) identity, authorization is way to know what kind of access is that user is granted, marking the periphery one is allowed to wander.

JWT

When it comes to web, mobile or even a desktop applications per say, authentication is very much important to scope the user to its data at the same time protecting its data to be shared. HTTP is stateless by nature, so to establish an state; sessions are used to store data (either server side/client side) that can be shared/identified with every request by session id via cookies.

Why token based authentication are needed

When it comes to session based authentication, it has its limitations; cross domain restriction imposed by browsers, scaling (when sessions is stored on server side), multiple devises (especially when device does not implement/use cookies). Using Tokens allows one to leverage multiple devices, multiple domains as well as choose when to share tokens with requests

JWT or JSON Web Tokens

JSON Web Tokens are an open, industry standard RFC 7519 method for representing claims securely between two parties.

JSON Web Token (JWT) is an open standard, that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed. JWTs can be signed using a secret (with the HMAC algorithm) or even a public/private key pair using RSA or ECDSA.

JWT has many advantage, vast range of encryption algorithms to choose from, expiration, claims like issuer, subject, audience, not before, issued at etc, to secure it further.

Where JWT can be used

Although JSON Web Token’s are not restricted how and where it can be used. Here are some scenarios where it can be used widely

Authorization: By far, this is most common scenario for using JWT. When user successfully establishesh its identification for first time, server can issue a signed json web token to user. User in turn shares jwt in subsequent requests, allowing user access resources and/or services that user is allowed to

Information Exchange: JSON Web Tokens are a good way of securely transmitting information among parties. JWT can be signed using RSA public/private keypair, hence entrusting the information and sender are, who they are claiming to be

Structure

JSON Web Tokens are compact, compared to SAML and more secure than Simple Web Tokens. JWT has three parts header, payload and signature

Header: Header part of JWT consists of two parts, alg, signing algorithm being used to sign token (i.e HMAC SHA256 or RSA) and typ; type of token, that in this case would always be JWT

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

A Complete list of available signing algorithm can be found here

Payload: This is second part of token which can contain claims. Claims are statement about entity, that could be user or information to be exchanged. Claims can be categorized in three types

Signature: In JWT, signature is important part of token. It is used to establish authenticity and non-tempering of tokens. To create a signature JWT needs Base 64 encoded both header, payload and a secret salt. JWT will then use algorithm specified in header to sign the token. For example to sign a token with HMAC SHA256, JWT will do Following

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

The signature will be used to verify the message is not tempered with, by parties involved. And in case of assymetric keys it can also establish sender’s identity

How does JSON Web Token work

In authentication, when the user successfully logs in using their credentials, a JSON Web Token will be returned to user. Since tokens are credentials, great care must be taken to prevent security issues. In general, you should not keep tokens longer than required.

Token should must have an expiration time depending varying from application to application. You also should not store sensitive session data in browser storage due to lack of security.

Whenever the user wants to access a protected route or resource, the user agent should send the JWT, typically in the Authorization Header of HTTP request; using the Bearer schema. The content of the header should look like the following:

Authorization: Bearer <token>

This can be, in certain cases, a stateless authorization mechanism. The server’s protected routes will check for a valid JWT in the Authorization header, and if it’s present, the user will be allowed to access protected resources. If the JWT contains the necessary data, the need to query the database for certain operations may be reduced, though this may not always be the case.

If the token is sent in the Authorization header, Cross-Origin Resource Sharing (CORS) won’t be an issue as it doesn’t use cookies.

The following diagram shows how a JWT is obtained and used to access APIs or resources:

JWT Workflow

How does a JSON Web Token work

1.) The Application or client sends an authorization request to authorization endpoint with credentials

2.) A JSON Web Token is returned to user, If user identity is successfully established

3.) User shares that access token with subsequent requests to access protected api endpoints

Note: All the information contained within the signed token is exposed to users or other parties, even though they are unable to change it. This means you should not put secret information within the token.