Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JWT invalid signature

Tags:

java

jwt

I am trying to develop my app using json web token. I decided to use jjwt but it doesn't work. I have a following snippet

Jwts.parser()
        .setSigningKey(secretKey)
        .parseClaimsJws(token)
        .getBody()

which always throws exception.

I tried to generate token with the following code

String compactJws = Jwts.builder()
            .setSubject("Joe")
            .signWith(SignatureAlgorithm.HS256, "secret")
            .compact();

and when I pasted this token here https://jwt.io/ I got the information that it is invalid. What is wrong ?

like image 954
Andayz Avatar asked Oct 23 '25 15:10

Andayz


1 Answers

You're passing a plain text key in signWith method, that's the problem;

As per JJWT source code:

/** 
331      * Signs the constructed JWT using the specified algorithm with the specified key, producing a JWS. 
332      * 
333      * <p>This is a convenience method: the string argument is first BASE64-decoded to a byte array and this resulting 
334      * byte array is used to invoke {@link #signWith(SignatureAlgorithm, byte[])}.</p> 
335      * 
336      * @param alg                    the JWS algorithm to use to digitally sign the JWT, thereby producing a JWS. 
337      * @param base64EncodedSecretKey the BASE64-encoded algorithm-specific signing key to use to digitally sign the 
338      *                               JWT. 
339      * @return the builder for method chaining. 
340      */ 
341     JwtBuilder signWith(SignatureAlgorithm alg, String base64EncodedSecretKey); 
342 

343     /** 
344      * Signs the constructed JWT using the specified algorithm with the specified key, producing a JWS. 
345      * 
346      * @param alg the JWS algorithm to use to digitally sign the JWT, thereby producing a JWS. 
347      * @param key the algorithm-specific signing key to use to digitally sign the JWT. 
348      * @return the builder for method chaining. 
349      */ 
350     JwtBuilder signWith(SignatureAlgorithm alg, Key key); 

pass a base-64 string containing the key, or declare a Key object and pass the relevant information to build it. such as in the example:

byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary("c2VjcmV0");//this has to be base-64 encoded, it reads 'secret' if we de-encoded it
Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());

  //Let's set the JWT Claims
JwtBuilder builder = Jwts.builder().setId(id)
                                .setIssuedAt(now)
                                .setSubject(subject)
                                .setIssuer(issuer)
                                .signWith(signatureAlgorithm, signingKey);
like image 51
Daniel Arechiga Avatar answered Oct 26 '25 05:10

Daniel Arechiga



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!