/ Authentication

JSON Web Tokens for Authentication

When building an API-centric application or building a RESTful API, there are no sessions to be tracked while dealing with authentication. REST APIs are stateless. That produced a need to find another mechanism to handle the authentication. One solution is to use a token-based authentication mechanism. And for that, we are going to learn about JSON Web Tokens (JWT).

JWT Definition

JSON Web Token (JWT) is an open standard JSON-based object defined in RFC 7519 that assert claims for securely transmitting a digitally signed set of information using a secret or a public/private key pair.

JWTs are small in size which makes the data transmission between the server and the client faster and could be transmitted through HTTP header, URL, or even POST parameter.

JWTs could be used in different scenarios. However, the most widely used one is for authentication. Each request to a route or resource that is permitted with a JWT will include the token allowing a logged-in user to access that route or resource.

Authentication Process

The process usually follows this scenario. The user logs in with his/her credentials and a JWT will be returned and should be saved locally, typically in local storage, session storage, or a cookie. Then whenever the user agent sends a request to a protected route or resource, the JWT should be attached to the Authorization header using Bearer schema. It looks like the following.

Authorization: Bearer <token>

The server will get the JWT from the Authorization header, and allow or decline the access depending on its validity. The following figure presents the last process.

jwt-browser-server

The source of the image could be found here.

The statelessness of the JWT makes it an excellent fit for stateless data APIs, not mentioning that dealing with Cross-Origin Resource Sharing (CORS) is not an issue as the cookies are not used. Also, because JWTs are self-contained, the required information for authentication is in the token which eliminates the need to query the database.

How JWT Works

The token is composed of a header, a payload, and a signature separated by dots .. Therefore, it looks like the following: xxxx.yyyy.zzzz as header.payload.signature structure.

The header entails two parts: the used hashing algorithm, and the type of the token. HMAC SHA256 and RSA are some of the examples of the hashing algorithms, and the type of the token is JWT. The header will be Base64Url encoded forming the first part of the JSON Web Token.

The following is an example of the header.

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

The payload consists of the claims. Claims are the data of the entity, which is usually the user, and other metadata. They are divided into three types: public, private, and reserved. The public claims are defined by the users of the JWTs and should be defined as a URI that has a collision resistant namespace or identified in the IANA JSON Web Token Registry. The private claims are the customized claims that are created for sharing the information between the server and the client agent. The reserved claims are the recommended predefined claims, which their names are three characters long. The following is a list of some reserved claims.

  • iss: Is the issuer of the JWT.
  • sub: Is the subject of the JWT.
  • aud: Is the audience of the JWT. The audience represents the intended recipients of the JWT.
  • exp: Is the expiration time of the JWT.
  • iat: Is the "issued at" claim that identifies the issue time of the JWT.
  • jti: Is a unique, case-sensitive JWT ID.

The payload will be Base64Url encoded forming the second part the JWT. The following is an example of the payload.

{
    "sub": "0987654321",
    "name": "John Doe",
    "id": 98743,
    "admin": true
}

The signature is the last part of the token which consists of the sign of the encoded header, the encoded payload, a secret string, and the algorithm the has been specified in the header. It is used for verifying the sender of the JWT and determining that the message has not been tampered with while it has been sent. The following shows how to create a signature using the HMAC SHA256 algorithm.

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

Adding all the previous parts together forms the token. The following is an example of a signed JWT.

jwt-token

The source of the image could be found here.

Other Authentication Solutions

JSON Web Tokens are not the only solution when it comes to stateless authentication or sharing information securely, some other options exist, like Security Assertion Markup Language Tokens (SAML), and Simple Web Tokens (SWT) and both options use XML to transfer data.

However, JWTs have the prosperity of using JSON instead of XML where the prior is less verbose and smaller in size when encoded than the last.

Usage-wise, JWT is suitable for multiple platforms (like the web, and mobile) due to the easiness of the processing it. For example, JSON parsers map to objects directly in most of the programming languages, while XML does not have this natural mapping.

Security-wise, SWT can use HMAC algorithm to symmetrically sign a token with a secret, while JWT can use public/private key pairs. However, SAML can use the last approach, but signing XML with XML Digital Signature is very difficult comparing it to signing JSON. The following figure shows the length of an encoded JWT compared to an encoded SAML.

comparing-jwt-vs-saml2

The source of the image could be found here.

Anas Shekhamis

Anas Shekhamis

A software engineer who specializes in architecting and developing web applications. On a daily basis, I use Python, JavaScript, Ruby, and PHP to design and implement API's and build web applications.

Read More
JSON Web Tokens for Authentication
Share this