(JWT) JSON Web Tokens for API

Pankaj Baagwan
ducktyp’d
Published in
5 min readJun 1, 2020

This post was originally published here on July, 01, 2017

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

When it comes to the web, mobile, or even desktop applications per se, 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 a 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 is 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 devices (especially when the 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 advantages, a 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 to how and where it can be used. Here are some scenarios where it can be used widely

Authorization: By far, this is the most common scenario for using JWT. When a user successfully establishes its identification for the first time, the server can issue a signed JSON web token to the 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 the second part of the token which can contain claims. Claims are a statement about the entity, that could be user or information to be exchanged. Claims can be categorized into three types

  • Registered Claims: These are predefined sets of claims. These claims are not mandatory but useful and hence recommended. Some of the claims are iss (issuer), exp (expiry), sub (subject), etc. For full list of registered claims please go through RFC7519
  • Public Claims: These claims can be defined by JWT users, but since being in the public domain these need to be maintained at centralized registry like JSON Web Token Registry to avoid collisions
  • Private Claims: These are private claims defined by JWT user applications or parties as agreed upon to share information.

Signature: In JWT, signature is an important part of the 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 the algorithm specified in the 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 tampered with, by parties involved. And in case of asymmetric 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 the 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 have an expiration time depending on varying from application to application. You also should not store sensitive session data in browser storage due to a 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:

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.

--

--

Pankaj Baagwan
ducktyp’d

Architect, Tech Innovator, Certified Ethical Hacker and Cyber Security Enthusiast