How to Generate JWT Token in Spring Boot Easily
To generate a
JWT token in Spring Boot, use the io.jsonwebtoken.Jwts builder to create a token with claims, a secret key, and expiration. Then sign it with an algorithm like HS256 and compact it to a string for client use.Syntax
The basic syntax to generate a JWT token in Spring Boot uses the Jwts.builder() method chain:
setSubject(): sets the user or subject identifier.setIssuedAt(): sets the token creation time.setExpiration(): sets when the token expires.signWith(): signs the token with a secret key and algorithm.compact(): builds the final token string.
java
String jwt = Jwts.builder() .setSubject("user123") .setIssuedAt(new Date()) .setExpiration(new Date(System.currentTimeMillis() + 3600000)) // 1 hour .signWith(Keys.hmacShaKeyFor(secretKey.getBytes()), SignatureAlgorithm.HS256) .compact();
Example
This example shows a simple Spring Boot method that generates a JWT token for a username with a 1-hour expiration using a secret key.
java
import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import io.jsonwebtoken.security.Keys; import java.util.Date; import javax.crypto.SecretKey; public class JwtTokenGenerator { private static final String SECRET = "mysecretkeymysecretkeymysecretkey12"; // 32 chars public static String generateToken(String username) { SecretKey key = Keys.hmacShaKeyFor(SECRET.getBytes()); return Jwts.builder() .setSubject(username) .setIssuedAt(new Date()) .setExpiration(new Date(System.currentTimeMillis() + 3600000)) // 1 hour .signWith(key, SignatureAlgorithm.HS256) .compact(); } public static void main(String[] args) { String token = generateToken("user123"); System.out.println("Generated JWT Token: " + token); } }
Output
Generated JWT Token: eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1c2VyMTIzIiwiaWF0IjoxNjg4NzY4MDAwLCJleHAiOjE2ODg3NzE2MDB9.abc123xyz456...
Common Pitfalls
Common mistakes when generating JWT tokens in Spring Boot include:
- Using a secret key that is too short or weak, causing security risks or errors.
- Not setting an expiration time, which can lead to tokens that never expire.
- Using deprecated
signWith()methods without specifying the key type. - Encoding the secret key incorrectly (should be bytes, not string directly).
Always use a strong, sufficiently long secret key and the latest io.jsonwebtoken API.
java
/* Wrong way: short key and deprecated signWith usage */ String token = Jwts.builder() .setSubject("user") .signWith(SignatureAlgorithm.HS256, "shortkey") // Deprecated and insecure .compact(); /* Right way: use Keys.hmacShaKeyFor and byte array key */ SecretKey key = Keys.hmacShaKeyFor("myverylongsecretkeymyverylongsecretkey".getBytes()); String token = Jwts.builder() .setSubject("user") .signWith(key, SignatureAlgorithm.HS256) .compact();
Quick Reference
Remember these tips when generating JWT tokens in Spring Boot:
- Use
io.jsonwebtokenlibrary for easy token creation. - Always set
setSubject(),setIssuedAt(), andsetExpiration(). - Use a strong secret key with at least 256 bits (32 characters).
- Sign tokens with
HS256algorithm usingKeys.hmacShaKeyFor(). - Never expose your secret key in public code or repositories.
Key Takeaways
Use io.jsonwebtoken.Jwts.builder() with setSubject, setIssuedAt, setExpiration, and signWith to generate JWT tokens.
Always use a strong, sufficiently long secret key with Keys.hmacShaKeyFor for signing.
Set token expiration to avoid security risks from never-expiring tokens.
Avoid deprecated signWith methods; specify key and algorithm explicitly.
Keep your secret key secure and never hardcode it in public code.