how to get claims value from JWT token authentication

I have set claims in JWT token in the token provider. now I want to get claim value through authentication when API is hit.

I have checked in Principal, details, credential, authorities but I am not getting claims in any of them.

Claims claims = Jwts.claims().setSubject(authentication.getName());
    claims.put(AUTHORITIES_KEY, authorities);
    claims.put("userId", userRepo.findUserIdByUsername(authentication.getName()));

return Jwts.builder()
.setSubject(authentication.getName())
.setClaims(claims)
//.claim(AUTHORITIES_KEY, authorities)
.signWith(SignatureAlgorithm.HS512, SIGNING_KEY)
.setIssuedAt(new Date(System.currentTimeMillis()))
.setExpiration(new Date(System.currentTimeMillis() + ACCESS_TOKEN_VALIDITY_SECONDS*1000))
.compact();

I want to get “userId” claim from the authentication or any other way to get claims value from token.

#java #spring

3 Likes132.10 GEEK