'How To set and get content of Payload in JWT Token
I have created a JWT Token in Spring Boot for storing User Details. When I use Jwttokenutil.getUsernameFromToken(authToken) [ authToken is the token passed ] method I get the data set to Subject. Similarly I want to get the data set to Payload which contains other User Details. But I am not able to get it.
======= Below is my token generation method / code : ========
public String generateToken(HashMap<String, Object> userData,String subject)
{
String jwtToken="";
System.out.println("in generate token method : " + subject);
jwtToken = Jwts.builder()
.setSubject(subject) // subject is dbname
.claim("userDetails", userData)
.setPayload(userData.toString())
.setIssuedAt(new Date())
.setExpiration(new Date(System.currentTimeMillis() + 60*60*5*1000))
.signWith(SignatureAlgorithm.HS256, "secretkey")
.compact();
System.out.println("userData " + userData);
return jwtToken;
}
======= Below is the method I have created to get the Payload data ======
public Object getPayloadFromToken(String token)
{
Claims body= Jwts.parser()
.setSigningKey("secretkey")
.parseClaimsJws(token)
.getBody();
System.out.println("userdet==========> " + body.get("userDetails") );
return body.get("userDetails");
}
=== But I am getting this error ===
java.lang.IllegalStateException: Both 'payload' and 'claims' cannot both be specified. Choose either one.
Solution 1:[1]
Late but I hope it serves someone. .setPayload (...) is used to create a payload defined by us, the error that you get with claims is because .setPayload (...) should not be used with any of the following .setSubject (...) .claim (...) .setIssuedAt (....) .setExpiration (...)
Solution 2:[2]
Hi Sorry for late Answer. Actually you can't add both claims and payload. You can user either only one method in that. Payload method accepts only string, So add values to the token you can use the method add claims. Follow the below code structure. It will generates proper JWT token using details.
public String generateToken(Authentication authentication) {
Details user = (Details) authentication.getPrincipal();
Map<String, Object> claims = new HashMap<>();
claims.put("name", user.getName());
claims.put("email", user.getEmail());
return Jwts.builder().setSubject(user.getUsername()).addClaims(claims)
.setIssuedAt(new Date())
.setExpiration(new Date((new Date()).getTime() + tokenExpirationTime))
.signWith(SignatureAlgorithm.HS512, secretKey).compact();
}
Follow this method need any updates and changes. Please comment below....
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Alvaro Gutierrez |
Solution 2 | Santil |