JJWT parse dont fail if SigningKey is slightly different

479 Views Asked by At

I try to create JWT token

final String jws = Jwts.builder()
            .claim("rainId", rainId.toString())
            .signWith(SignatureAlgorithm.HS256, TextCodec.BASE64.decode("jwtSecretKey"))
            .compact();

Then I try to parse it

Jws<Claims> jwsClaims = Jwts.parser()
                .require("rainId", rainId.toString())
                .setSigningKey(TextCodec.BASE64.decode("jwtSecretKey1"))
                .parseClaimsJws(jws);

As you can see SigningKey is slightly different, so I expect that parser will fail, but it doesnt happen. It happen only if SigningKey in parser have very big difference. For example "jwtSecretKey1111111111111111111111111111111" or "dsfdsfdsfdsfds". Can some one explain why parser not fail if SigningKey in parser is slightly different?

I use

<dependency>
  <groupId>io.jsonwebtoken</groupId>
  <artifactId>jjwt</artifactId>
  <version>0.9.1</version>
</dependency>
1

There are 1 best solutions below

0
cassiomolin On BEST ANSWER

You don't seem to be using the API properly.

Both signWith() and setSigningKey() methods expect a Base64-encoded String as input. But you are invoking TextCodec.BASE64.decode("...").

Both jwtSecretKey and jwtSecretKey1 don't look like Base64-encoded strings. However, if you attempt to decode them, they will produce the same output:

System.out.println(Arrays.toString(TextCodec.BASE64.decode("jwtSecretKey")));
System.out.println(Arrays.toString(TextCodec.BASE64.decode("jwtSecretKey1")));
[-113, 11, 82, 121, -54, -34, -76, -89, -78]
[-113, 11, 82, 121, -54, -34, -76, -89, -78]

And that's why the signature validation doesn't fail.

You should use TextCodec.BASE64.encode("...") instead, as shown below:

String jws = Jwts.builder()
        .claim("rainId", rainId.toString())
        .signWith(SignatureAlgorithm.HS256, TextCodec.BASE64.encode("jwtSecretKey"))
        .compact();

Jws<Claims> jwsClaims = Jwts.parser()
        .require("rainId",rainId.toString())
        .setSigningKey(TextCodec.BASE64.encode("jwtSecretKey1"))
        .parseClaimsJws(jws);