JWT Authentication : Generate JWT
- JWT is an open source standard used to securely share information between client-server applications.
- Using JWT, we can Generate tokens and Validate tokens.
* 1. JWT Structure
- Header: Contains algorithm and token type
{
"alg": "HS256", The algorithm used to sign the JWT
"typ": "JWT" The media type of this complete JWT
}
{
"sub": "1234567890", The subject of the JWT (the user)
"name": "alamgir",
"iat": 1516239022 The time at which the JWT was issued.
}
2. Cryptography Concepts
SHA-256 (Secure Hash Algorithm 256-bit)
- Cryptographic hash function
- Fixed output: 256 bits (32 bytes / 64 hex chars)
- One-way (irreversible)
- Same input → same hash
- Small input change → big output change
- Hard to find collisions (two inputs with same hash)
- Used in passwords, signatures, integrity checks, blockchain
HMAC (Hash-based Message Authentication Code)
- Uses a secret key + hash function (e.g., SHA-256)
- Output length depends on the hash function (e.g., 256 bits for SHA-256)
- Provides integrity (data not altered)
- Provides authenticity (from trusted sender)
- Resistant to tampering and length-extension attacks
- Used in APIs, JWTs, secure tokens, SSL/TLS
HS256 Signing Algorithm
- HMAC with SHA-256
- Symmetric key algorithm:
- One secret key shared between sender and receiver
- Same key used for generating and validating the signature
3. JWT Creation Steps
- Header → Base64 (
b64Header) - Payload → Base64 (
b64Payload) - Combine:
headerPayload = b64Header + "." + b64Payload - Signature:
HMAC-SHA256(secretKey, headerPayload) - Encode signature → Base64(hash)
-
JWT:
jwt = b64Header + "." + b64Payload + "." + hash -
We can verify output at jwt.io
Token Validation
- Check expiration time: compare
expiredclaim with current time - Extract username from token: compare with request username
Create token,Validate JWT token
package com.alamgir.l_spring_boot_security_jwt.security;
import java.util.Date;
import javax.crypto.SecretKey;
import org.springframework.stereotype.Component;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
@Component
public class JwtUtil {
private final String SECRET_KEY = "F3r7lG7OZt+2k4Q0l9U+7Vq2g6LkpB1D8uVhb3cW+rY="; // Base64 256-bit key
private final long TOKEN_EXPIRY_DURATION = 5 * 60 * 1000; // 5 mins
public SecretKey getSecretKey() {
byte[] keyBytes = Decoders.BASE64.decode(SECRET_KEY);
return Keys.hmacShaKeyFor(keyBytes);
}
// Create JWT Token
public String createToken(String username) {
return Jwts.builder()
.subject(username)
.issuedAt(new Date(System.currentTimeMillis()))
.expiration(new Date(System.currentTimeMillis() + TOKEN_EXPIRY_DURATION))
.signWith(getSecretKey()) // "alg": "HS256", "typ": "JWT" auto-set //! JJWT automatically sets `"alg": "HS256"` when using an HMAC key.It also adds `"typ": "JWT"` to mark the token as a JSON Web Token.
.compact();
}
// Decode and Extract username
public String extractUsername(String token) {
return Jwts.parser()
.verifyWith(getSecretKey())
.build()
.parseSignedClaims(token)
.getPayload()
.getSubject();
}
// Check if token is expired
public boolean isTokenExpired(String token) {
Date expiryTime = Jwts.parser()
.verifyWith(getSecretKey())
.build()
.parseSignedClaims(token)
.getPayload()
.getExpiration();
return expiryTime.before(new Date());
}
// Validate token
public boolean isValidToken(String token, String requestedUsername) {
String usernameFromToken = extractUsername(token);
return usernameFromToken.equalsIgnoreCase(requestedUsername)
&& !isTokenExpired(token);
}
}
4.Override and Integration Spring Security with JWT
1. Add Spring Boot Security Starter
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
<version>3.5.6</version>
</dependency>
- By default, APIs show 401 Unauthorized
- Default credentials in console:
username / password
2. Add JJWT Library
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.13.0</version>
</dependency>