Chaos Rules
Chaos Rules

Reputation: 520

How can I get Claims from a JWT?

I need to extract claims from a JWT.

It seems that this should be a no-brainer.

It was signed, from the header I get:

{
  "alg": "RS256",
  "typ": "JWT"
}

JWT:

eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOiJtYXJrLnN0YW5nQGRoaWdyb3VwaW5jLmNvbSIsInNjb3BlIjpbIm9wZW5pZCJdLCJyb2xlcyI6WyJKT0JTRUVLRVIiXSwiam9ic2Vla2VySWQiOiJ3TDFkTWdQckZWOUl5dEZZIiwiZXhwIjoxNDg4Mzk1ODE5LCJhdXRob3JpdGllcyI6WyJKT0JTRUVLRVIiXSwianRpIjoiNWRiYjNkYzQtNGI3NC00MDYyLTgzMmQtYjE1MTgwYWZhZjllIiwiY2xpZW50X2lkIjoiZWZjIn0.NxiF4x39na3KdDUFz2zxqy1zSfJkj4FdKHflpgJUxzMgBq8bbJIFVkmwAUYA6_YXm6kGFcyTMgdiRIJpqc5buDPdV1vkzh4QKFTxMz9MF4i3vtIQ21Vm5W12KikWdWGGUXMD4udJwu7rmuIBtNIa-ciZOPADNrrXfuw7iML1xxAA-C0f4OTbiKqiXr3QEUZwcqZB17qfh_dVRRxgO-_uHUg84JDcpXEDQPzPWX68u1EHH4J6IcpMKn1VY9k3RcZU6pq-ndzQgBlKdVm2owA6i-UM9p1zSz7ZX_2wx0czEEcNF1rMdeIv5yxP9YEpWb14-GUG4qgpn_rAIQBJ7eu7xw

It decodes on the jwt.io site just fine, but since I don't have the "secret" key, it comes up as "invalid signature". Which is fine, I am not trying to validate it.

All I want is the claims but when I use a Java library to decode it I get nothing but errors.

If I decode it manually (i.e. split/base64 decode) it is fine.

So, what am I doing wrong with the Java libraries?

Upvotes: 6

Views: 21050

Answers (2)

cassiomolin
cassiomolin

Reputation: 131187

Once the question is tagged with , I understand you are using jose4j for parsing JWT tokens.

In this situation, you can invoke setSkipSignatureVerification() from the JwtConsumerBuilder. It allows you to parse the claims without validating the signature:

JwtConsumer jwtConsumer = new JwtConsumerBuilder()
                                  .setSkipSignatureVerification()
                                  .build();
                                                  
JwtClaims jwtClaims = jwtConsumer.processToClaims(jwt);

Upvotes: 9

Keet Sugathadasa
Keet Sugathadasa

Reputation: 13572

Let me provide a general answer for everyone's use.

I am using this maven/gradle library. Use the following for Maven.

<dependency>
    <groupId>com.nimbusds</groupId>
    <artifactId>nimbus-jose-jwt</artifactId>
    <version>[ version ]</version>
</dependency>

Then use the following code to decode and get claims.

String jwtToken = "eyJ0eXAiOiJKV1QiLCJhbG...";

JWSObject jwsObject;
JWTClaimsSet claims;

try {
       jwsObject = JWSObject.parse(this.jwt);
       claims =  JWTClaimsSet.parse(jwsObject.getPayload().toJSONObject());
} catch (java.text.ParseException e) {
       // Invalid JWS object encoding
}

// now access any claims you want using the relevant key. It will be returned as an object
Object expiry = claims.getClaim("exp");


Upvotes: 3

Related Questions