0
0
Spring Bootframework~5 mins

JWT generation in Spring Boot

Choose your learning style9 modes available
Introduction

JWT generation creates a secure token to identify users safely. It helps servers know who is making requests without asking for passwords every time.

When you want users to log in once and stay logged in securely.
When your app needs to check user identity on many requests without storing session data.
When building APIs that need to verify user permissions quickly.
When you want to share user info safely between different parts of your app.
Syntax
Spring Boot
String jwt = Jwts.builder()
    .setSubject(username)
    .setIssuedAt(new Date())
    .setExpiration(new Date(System.currentTimeMillis() + expirationTime))
    .signWith(Keys.hmacShaKeyFor(secretKey.getBytes()), SignatureAlgorithm.HS256)
    .compact();

setSubject sets the user identity inside the token.

signWith uses a secret key to make the token secure and hard to fake.

Examples
Simple token with only user ID and signature.
Spring Boot
String token = Jwts.builder()
    .setSubject("user123")
    .signWith(Keys.hmacShaKeyFor("mySecretKeymySecretKeymySecretKeymySecretKey".getBytes()), SignatureAlgorithm.HS256)
    .compact();
Token with issue time and expiration set to 1 hour later.
Spring Boot
String token = Jwts.builder()
    .setSubject("user123")
    .setIssuedAt(new Date())
    .setExpiration(new Date(System.currentTimeMillis() + 3600000))
    .signWith(Keys.hmacShaKeyFor("mySecretKeymySecretKeymySecretKeymySecretKey".getBytes()), SignatureAlgorithm.HS256)
    .compact();
Sample Program

This Spring Boot compatible Java class creates a JWT token for a username. It sets the token to expire in 1 hour and signs it with a secret key. The main method prints the token.

Spring Boot
package com.example.jwt;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import java.util.Date;
import javax.crypto.SecretKey;

public class JwtGenerator {
    private static final String SECRET_KEY_STRING = "mySecretKeymySecretKeymySecretKeymySecretKey";
    private static final SecretKey SECRET_KEY = Keys.hmacShaKeyFor(SECRET_KEY_STRING.getBytes());
    private static final long EXPIRATION_TIME = 3600000; // 1 hour in milliseconds

    public static String generateToken(String username) {
        return Jwts.builder()
            .setSubject(username)
            .setIssuedAt(new Date())
            .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
            .signWith(SECRET_KEY, SignatureAlgorithm.HS256)
            .compact();
    }

    public static void main(String[] args) {
        String token = generateToken("user123");
        System.out.println("Generated JWT Token:");
        System.out.println(token);
    }
}
OutputSuccess
Important Notes

Keep your secret key safe and never share it publicly.

Tokens expire to keep security strong; always set expiration.

Use libraries like jjwt for easy JWT handling in Spring Boot.

Summary

JWT tokens securely identify users without storing sessions.

Use a secret key to sign tokens and set expiration times.

Spring Boot apps can generate JWTs using the jjwt library easily.