16

I don't want to verify the JWT using the secret key (which I don't have), I only want to decode the JWT and read the payload. Can this be achieved using jsonwebtoken.io:jjwt? It seems like there is a method missing in the API.

Of course, I could split-&-Base64-decode the token myself but it feels like the most basic functionality one would expect from a JWT-library; hence I suspect I am missing something.

E_net4
  • 27,810
  • 13
  • 101
  • 139
Jaroslav Záruba
  • 4,694
  • 5
  • 39
  • 58

3 Answers3

29

Try the following code:

int i = jws.lastIndexOf('.')
String withoutSignature = jws.substring(0, i+1);
Jwt<Header,Claims> untrusted = Jwts.parser().parseClaimsJwt(withoutSignature);

You can 'chop off' the last 'part' after the last period character ('.'), which is the JWS signature.And then read that JWT as a 'normal' JWT (non-JWS).

What you are asking for is to ignore the signature on a valid JWS and read the JWT header and body anyway. This violates the JWS specification, and because of that JJWT does not support it.

This is taken from this github issue, which I guess is same as you are facing.

bidisha mukherjee
  • 715
  • 1
  • 10
  • 20
4

Maybe use the Auth0 library instead?

DecodedJWT jwt = JWT.decode(token);
jwt.getToken();

Dependencies:

<dependency>
  <groupId>com.auth0</groupId>
  <artifactId>java-jwt</artifactId>
  <version>3.8.3</version>
</dependency>
<dependency>
  <groupId>com.auth0</groupId>
  <artifactId>jwks-rsa</artifactId>
  <version>0.9.0</version>
</dependency>

Example taken from https://medium.com/trabe/validate-jwt-tokens-using-jwks-in-java-214f7014b5cf

Blink
  • 1,408
  • 13
  • 21
1

If you can use another library, it can be done as accepted answer here: How to decode JWT token to get details of Header and Payload using nimbus-jose-jwt?

Repeating the answer here:
dependency: com.nimbusds:nimbus-jose-jwt:<version>
usage:

/**
 * accessToken: the JWT string text.
**/
private String parseJWT(String accessToken) {
    try {
        var decodedJWT = SignedJWT  // or PlainJWT or EncryptedJWT
                           .parse(accessToken);
        var header = decodedJWT.getHeader().toString();
        var payload = decodedJWT.getPayload().toString();
    } catch (ParseException e) {
        throw new Exception("Invalid token!");
    }
}