Skip to content
Advertisement

How do I get a custom field out of the payload using JJWT

OK, I am adding a couple of custom claims to the payload when I generate the JWT, and I can pull those out just fine in my front-end (javascript). I then have my javascript send an ajax call to a micro-service and it passes the JWT along with it. I want to get my custom claims out of the JWT in the micro-service. I’m doing the following:

Claims claims = Jwts.parser().setSigningKey(Vars.SECRET_KEY).parseClaimsJws(token).getBody();
 User user = claims.get("customuser", User.class);

and it throws an exception.

io.jsonwebtoken.RequiredTypeException: Expected value to be of type: class net.netdatacorp.netdauth.model.User, but was class java.util.LinkedHashMap
    at io.jsonwebtoken.impl.DefaultClaims.get(DefaultClaims.java:128)

Here is how the data looks in the JWT inspector on the front-end for my custom claim.

{
  jti: "83bffbad-7d36-4370-9332-21a84f2a3dce",
  iat: 1498241526,
  sub: "test",
  iss: "www.test.net",
  customuser: {
    userId: 1,
    userCd: "TMM",
    firstNm: "Testy",
    lastNm: "McTesty",
    userNm: "test",
    emailAddress: "jacob@test.net",
    active: true,
    createdDt: 1491355712000,
    createdByUserId: 0,
    lastUpdateDt: 1498199278000,
    lastUpdateByUserId: 0,
    lastLoginDt: 1484928016000
  }
}

What am I missing to be able to pull my custom claim out?

Advertisement

Answer

OK, so I switched to using Jose4J instead of JJWT and after working to get every thing working I realized I probably could have done something similar with JJWT. So what I ended up doing was to use Gson to perform a JSON encoding of the Object and the attaching the resulting JSON string as a claim. And so when I wanted to get a custom claim back out, I would extract the claim as a string and the use the Gson library to convert it back to a POJO.

GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();

JwtConsumer jwtConsumer = getConsumer();

JwtClaims jwtClaims = jwtConsumer.processToClaims(token);
String userStr = jwtClaims.getClaimValue("user", String.class);
User user = gson.fromJson(userStr, User.class);
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement