JWT tokens help keep users logged in safely without saving passwords everywhere. They prove who you are in a simple way.
0
0
Authentication with JWT token in Spring Boot
Introduction
When you want users to log in once and stay logged in while using your app.
When you need to check user identity on many parts of your app without asking for password again.
When building APIs that need secure access from different devices or apps.
When you want a simple way to share user info between frontend and backend securely.
Syntax
Spring Boot
String token = Jwts.builder()
.setSubject(username)
.setIssuedAt(new Date())
.setExpiration(new Date(System.currentTimeMillis() + expirationTime))
.signWith(SignatureAlgorithm.HS512, secretKey)
.compact();This code creates a JWT token with a username, issue time, expiration, and a secret key.
Use a strong secret key and keep it safe to protect your tokens.
Examples
This creates a token for user "user123" valid for 1 day using HS256 algorithm.
Spring Boot
String token = Jwts.builder()
.setSubject("user123")
.setIssuedAt(new Date())
.setExpiration(new Date(System.currentTimeMillis() + 86400000)) // 1 day
.signWith(SignatureAlgorithm.HS256, "mySecretKey")
.compact();This extracts the username from a JWT token using the secret key.
Spring Boot
Claims claims = Jwts.parser()
.setSigningKey("mySecretKey")
.parseClaimsJws(token)
.getBody();
String username = claims.getSubject();Sample Program
This program creates a JWT token for user "alice" valid for 1 hour, then reads the username back from the token.
Spring Boot
package com.example.demo; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import io.jsonwebtoken.Claims; import java.util.Date; public class JwtExample { private static final String SECRET_KEY = "mySecretKey12345"; private static final long EXPIRATION_TIME = 3600000; // 1 hour in ms public static String generateToken(String username) { return Jwts.builder() .setSubject(username) .setIssuedAt(new Date()) .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME)) .signWith(SignatureAlgorithm.HS512, SECRET_KEY) .compact(); } public static String validateTokenAndGetUsername(String token) { Claims claims = Jwts.parser() .setSigningKey(SECRET_KEY) .parseClaimsJws(token) .getBody(); return claims.getSubject(); } public static void main(String[] args) { String token = generateToken("alice"); System.out.println("Generated Token: " + token); String username = validateTokenAndGetUsername(token); System.out.println("Username from token: " + username); } }
OutputSuccess
Important Notes
Always keep your secret key private and never share it.
Tokens have expiration times to limit how long they are valid.
Use HTTPS to protect tokens when sent over the internet.
Summary
JWT tokens let you prove who you are without sending passwords repeatedly.
Spring Boot uses libraries like jjwt to create and check tokens easily.
Keep tokens safe and use expiration to improve security.