'JWT Signing in NodeJS and but unable to verify in Java

I want to pass a JWT token from a NodeJS service to another service in Java. However, based on the what I've tried, the token is always invalid whenever I try to verify it on the Java side. I do understand the JWT is platform-independent but I'm not able to figure out why is the token not able to get verified on the Java side.

Error: io.jsonwebtoken.security.SignatureException: JWT signature does not match locally computed signature. JWT validity cannot be asserted and should not be trusted

NodeJS signing the token (using express-jwt library)

    const jwtPayload = { id: "admin" };
    const secret = " ... some secret ...";
    const jwtData = { expiresIn: 2h };
    const access_token = jwt.sign(jwtPayload, secret, jwtData);

Java verifying the token (using io.jsonwebtoken)

String secret = "...same as on the nodejs side"
String accessToken = " .. access_token from nodejs .. "
String username = Jwts.parserBuilder().setSigningKey(secret).build().parseClaimsJws(accessToken).getBody().getSubject();

I have not set any additional options either on the NodeJS side or the Java side. Am I missing some configuration on either of the platforms? Or should I be using a different library?



Solution 1:[1]

In my case, solved like this:

GENERATE JWT IN EXPRESS:

jwt.sign({ issuer: new Date(), roles, exp: Math.floor(Date.now() / 1000) + (43200) }, SECRET, {
      algorithm: 'HS256',
      subject: username,
      jwtid: jwtId,
    }, (err, token) => {
      if (err) {
        logger.error(util.inspect(err));
      }
      resolve({ token, jwtId });
    });

IN JAVA I READ USING "SECRET".getBytes("UTF-8"):

Claims claims = Jwts.parser().setSigningKey("SECRET".getBytes("UTF-8")).parseClaimsJws(token).getBody();
            request.setAttribute("claims", claims);

Solution 2:[2]

I think the issue is the string secret. By calling getBytes("UTF-8") on your secret and providing signWith() with the byte[], everything will work out.

String username = Jwts.parser()
                    .setSigningKey(secret.getBytes("UTF-8"))
                    .parseClaimsJws(accessToken)
                    .getBody()
                    .getSubject();

(Also need to catch the UnsupportedEncodingException!)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Yurifull
Solution 2 ahsan