To add a user ID (or any custom claim) to a JWT token in a Java Spring Boot application, you typically use a JWT library like jjwt (Java JWT) or java-jwt by Auth0. Below, I'll show you a simple example using jjwt to create a JWT token with a user ID claim.
Step-by-step guide to add user ID to JWT token in Spring Boot
1. Add dependency
If you are using jjwt, add this to your pom.xml:
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.11.5</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.11.5</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId> <!-- or jjwt-gson if you prefer -->
<version>0.11.5</version>
<scope>runtime</scope>
</dependency>
2. Generate JWT with user ID claim
Here is a simple example of generating a JWT token with a user ID claim:
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import java.security.Key;
import java.util.Date;
public class JwtTokenProvider {
// Secret key for signing the token (use a strong key in production)
private final Key key = Keys.secretKeyFor(SignatureAlgorithm.HS256);
// Token validity in milliseconds (e.g., 1 hour)
private final long validityInMilliseconds = 3600000;
public String createToken(String userId) {
Date now = new Date();
Date expiryDate = new Date(now.getTime() + validityInMilliseconds);
return Jwts.builder()
.setSubject(userId) // You can also use setSubject for userId or username
.claim("userId", userId) // Custom claim
.setIssuedAt(now)
.setExpiration(expiryDate)
.signWith(key)
.compact();
}
}
3. Usage example
public class JwtDemo {
public static void main(String[] args) {
JwtTokenProvider tokenProvider = new JwtTokenProvider();
String userId = "12345";
String token = tokenProvider.createToken(userId);
System.out.println("JWT Token: " + token);
}
}
4. Parsing the token and extracting user ID
To extract the user ID from the token:
public String getUserIdFromToken(String token) {
return Jwts.parserBuilder()
.setSigningKey(key)
.build()
.parseClaimsJws(token)
.getBody()
.get("userId", String.class);
}
Summary
- Use
setSubject() or claim() to add user ID to the JWT.
- Sign the token with a secret key.
- Parse the token with the same key to extract claims.
If you want, I can also provide an example using java-jwt (Auth0) or integrate this with Spring Security. Just let me know!