JJWT: How to parse claims correctly?

aerojas picture aerojas · May 25, 2017 · Viewed 7.6k times · Source

I made a test JWT using something like the following code

String jwt = Jwts.builder()
    .setHeaderParam("typ", "jwt")
    .setId("myid")
    .setIssuer("ExampleIssuer")
    .setSubject("JohnDoe")
    .setIssuedAt(Date.from(LocalDateTime.now().toInstant(ZoneOffset.ofHours(-4))))
        .setExpiration(Date.from(LocalDateTime.now().toInstant(ZoneOffset.ofHours(-4)).plusSeconds(600)))
    .claim("perms",perms)
    .signWith(SignatureAlgorithm.HS512, "SECRET")
    .compact();

"perms" is a custom claim, which contains an ArrayList of Strings (permissions).

So when I receive the JWT back, I use the following code

try{
Jwt<?, ?> claims = Jwts.parser().setSigningKey("SECRET").parse(jwt); 
System.out.println(claims.getBody().toString());
} catch (SignatureException e){
//Error
}

And I get something like

{jti=myid, iss=ExampleIssuer, sub=JohnDoe, iat=1495678299, exp=1495678899, perms=[CREATE, VIEW]}

My question is: is this the correct (intended) way to get the claims back? It seems from now I will need to parse the result with a custom method, but I think somehow that is not the intended way.

Thank you.`

Answer

aerojas picture aerojas · May 25, 2017

I found a solution, not sure if the intended one, but it works. I need to use

Claims claims = new DefaultClaims();
        try{
            claims = Jwts.parser().setSigningKey("SECRET").parseClaimsJws(jwt).getBody();
        } catch (SignatureException e){
          //Signature error
        }

I can use Map methods on claims, but also the built-in methods to recover the individual claims:

String jti = claims.getId();
String iss = claims.getIssuer();
String sub = claims.getSubject();
String iat = claims.getIssuedAt().toString();
String exp = claims.getExpiration().toString();

@SuppressWarnings("unchecked")
ArrayList<String> perms = (ArrayList<String>) claims.get("perms");

I think I can suppress the warning on the unchecked casting because since I created the custom claim with the same value class, I know what to expect on it. Now the claims in the token are parsed correctly into variables I can work with.