What is a JWT?

Lakshay Parnami
4 min readMar 31, 2023

--

Introduction

JSON Web Tokens (JWT) is a popular method for securely transmitting information between parties as a JSON object. JWT is used for authentication and authorization in web applications and APIs. JWT consists of three parts: the header, the payload, and the signature. In this blog, we will take a closer look at how JWT works.

JWT Structure

JWT is composed of three parts separated by dots: header, payload, and signature.

The header contains information about the type of token and the cryptographic algorithms used to secure it. The header is a JSON object that includes two properties: “alg” and “typ”. The “alg” property specifies the cryptographic algorithm used to sign the token, such as HS256 or RS256. The “typ” property specifies the type of token, which is always set to “JWT”.

The payload contains the claims that provide information about the user or application. Claims can include any information that needs to be transmitted securely, such as user ID, name, email, role, and permissions. The payload is a JSON object that consists of a set of key-value pairs.

The signature is used to verify that the message has not been altered during transmission and that the sender is who they claim to be. The signature is calculated by hashing the header and payload with a secret key and signing the result with the specified algorithm.

How JWT works

When a user logs in, the server creates a JWT and sends it back to the client. The client can then include the JWT in the header of subsequent requests to the server. This allows the server to authenticate and authorize the user without having to store any session information on the server.

The server verifies the JWT by checking the signature and decoding the payload. If the signature is valid and the payload contains the necessary information, the server considers the user authenticated and authorized.

If the user needs to access a protected resource, such as a restricted API endpoint, the client includes the JWT in the request header. The server verifies the JWT and, if it is valid, grants access to the resource.

Advantages of JWT

JWT has several advantages over other authentication methods:

  1. Stateless: JWT is stateless, which means that the server does not need to keep track of session information. This reduces server overhead and improves scalability.
  2. Secure: JWT uses a cryptographic algorithm to sign the token, which ensures that the message has not been altered during transmission.
  3. Portable: JWT can be used across different domains and platforms, which makes it a useful tool for building microservices and APIs.

Dummy Code

Here’s an example interface and implementation for encoding and decoding JWTs in Java:

JWTService Interface:

public interface JWTService {
public String generateToken(Map<String, Object> claims, String secret, long expirationInMillis);

public Claims parseToken(String token);
}

JWTServiceImpl Implementation:

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;

import java.security.Key;
import java.util.Date;
import java.util.Map;

public class JWTServiceImpl implements JWTService {
private static final Key key = Keys.secretKeyFor(SignatureAlgorithm.HS256);

@Override
public String generateToken(Map<String, Object> claims, String secret, long expirationInMillis) {
return Jwts.builder()
.setClaims(claims)
.setExpiration(new Date(System.currentTimeMillis() + expirationInMillis))
.signWith(key, SignatureAlgorithm.HS256)
.compact();
}

@Override
public Claims parseToken(String token) {
return Jwts.parser()
.parseClaimsJws(token)
.getBody();
}
}

Explanation:

The JWTService interface defines two methods for encoding and decoding JWTs. The generateToken method takes in a map of claims, a secret key, and an expiration time in milliseconds, and returns a JWT string. The parseToken method takes in a JWT string and a secret key, and returns the parsed claims.

The JWTServiceImpl implementation uses the io.jsonwebtoken library to handle encoding and decoding of JWTs. The key variable is a secret key generated using the Keys class from the io.jsonwebtoken.security package.

The generateToken method uses the Jwts.builder() method to create a new JWT builder. The setClaims method sets the claims for the JWT, which is a map of key-value pairs. The setExpiration method sets the expiration time for the JWT. The signWith method signs the JWT with the secret key and algorithm specified. Finally, the compact method returns the JWT string.

The parseToken method uses the Jwts.parser() method to create a new JWT parser. The setSigningKey method sets the secret key for the parser. The parseClaimsJws method parses the JWT string and returns a Jws<Claims> object, from which we can extract the claims using the getBody method.

Note that in a real-world application, the secret key should be stored securely, and the expiration time should be carefully chosen based on the requirements of the application. Additionally, it’s important to validate the JWT when decoding it to ensure that it hasn’t been tampered with. This can be done using the validate method provided by the io.jsonwebtoken library.

Conclusion

JWT is a popular method for securely transmitting information between parties. It consists of a header, a payload, and a signature. The header contains information about the token, the payload contains the user or application information, and the signature verifies the authenticity of the message. JWT is stateless, secure, and portable, which makes it a useful tool for building web applications and APIs.

--

--

Lakshay Parnami

Hi, I’m Lakshay Parnami. I’m into Mobile Application Development, I work on Android, Flutter & React Native. I’m currently learning iOS development.