You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot中为JWT Token添加自定义Claims的实现方法

Got it, let's tackle how to add those custom claims—including your user object—to both the JWT Header and Payload in Spring Boot. I’ll walk you through practical, code-first steps that you can drop into your project right away.

1. Adding Custom Claims to JWT Payload

The Payload is where you’ll want to store most of your custom data (like the user object, plus standard claims iss, aud, exp, sub). We’ll use the popular JJWT library for this—if you don’t have it already, add the dependency to your pom.xml (or build.gradle):

For Maven:

<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>
    <version>0.11.5</version>
    <scope>runtime</scope>
</dependency>

Step 1: Make Your User Object Serializable

JJWT uses Jackson to serialize objects into JSON, so your User class needs to be serializable (no extra work if you have standard getters/setters):

public class User implements Serializable {
    private Long id;
    private String username;
    private String email;
    // Add getters, setters, and a constructor
}

Step 2: Generate the JWT with Custom Claims

Use JJWT’s Jwts.builder() to attach both standard and custom claims:

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.util.Date;

public String generateJwtToken(User user) {
    // Set token expiration (1 day in milliseconds)
    long expiryMillis = 86400000;
    Date expiryDate = new Date(System.currentTimeMillis() + expiryMillis);

    return Jwts.builder()
            // Standard JWT claims
            .setIssuer("your-app-name") // `iss` claim: token issuer
            .setAudience("your-target-users") // `aud` claim: intended audience
            .setExpiration(expiryDate) // `exp` claim: expiration date
            .setSubject(user.getUsername()) // `sub` claim: subject (usually username/user ID)
            // Custom claim: add your User object directly
            .claim("user", user)
            // Sign the token with a secure secret key (keep this safe!)
            .signWith(SignatureAlgorithm.HS512, "your-strong-secret-key-here")
            .compact();
}

Step 3: Extract the Custom User Object from the Token

When validating the token, you can pull the user claim back out easily:

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;

public User extractUserFromToken(String token) {
    Claims claims = Jwts.parserBuilder()
            .setSigningKey("your-strong-secret-key-here")
            .build()
            .parseClaimsJws(token)
            .getBody();

    // Extract the custom User object from claims
    return claims.get("user", User.class);
}
2. Adding Custom Claims to JWT Header

Headers typically store metadata like the signing algorithm (alg) and token type (typ), but you can add custom headers if needed. Use the setHeaderParam() method:

public String generateJwtWithCustomHeader(User user) {
    long expiryMillis = 86400000;
    Date expiryDate = new Date(System.currentTimeMillis() + expiryMillis);

    return Jwts.builder()
            // Custom header claims
            .setHeaderParam("custom-header-issuer", "your-app-name")
            .setHeaderParam("custom-header-key", "custom-value")
            // Payload claims (same as before)
            .setAudience("your-target-users")
            .setExpiration(expiryDate)
            .setSubject(user.getUsername())
            .claim("user", user)
            .signWith(SignatureAlgorithm.HS512, "your-strong-secret-key-here")
            .compact();
}

To extract header claims later:

import io.jsonwebtoken.Jws;

public void extractHeaderClaims(String token) {
    Jws<Claims> jws = Jwts.parserBuilder()
            .setSigningKey("your-strong-secret-key-here")
            .build()
            .parseClaimsJws(token);

    Map<String, Object> header = jws.getHeader();
    String customIssuer = (String) header.get("custom-header-issuer");
}
3. Key Things to Remember
  • Don’t store sensitive data: JWTs are Base64-encoded (not encrypted), so anyone can decode them. Never put passwords or private info in the user object or any claim.
  • Keep your secret key safe: Store it in environment variables, a config server, or a secure vault—never hardcode it in your codebase.
  • Validate claims: When parsing tokens, always check the exp (expiration) and other claims to ensure the token is valid.
  • Serializable objects: If your User has nested objects, make sure those are also serializable, or add Jackson annotations (like @JsonIgnore) for fields you don’t want to include.

内容的提问来源于stack exchange,提问作者Nasibulloh Yandashev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 10:07:36