FusionAuth / fusionauth-example-java-jwt

Java JWT usage
Apache License 2.0
2 stars 0 forks source link

Invalid signature for HS256 #1

Closed wunmiji closed 12 months ago

wunmiji commented 12 months ago

I used the example for HS256 at https://github.com/FusionAuth/fusionauth-example-java-jwt/blob/main/src/main/java/io/fusionauth/example/jwt/Hmac.java

the encoded token output says Invalid signature.

public static void main(String[] args) {
        // Build an HMAC signer using a SHA-256 hash
        Signer signer = HMACSigner.newSHA256Signer("too many secrets");

        // Build a new JWT with an issuer(iss), issued at(iat), subject(sub) and expiration(exp)
        JWT jwt = new JWT().setIssuer("www.acme.com")
                .setIssuedAt(ZonedDateTime.now(ZoneOffset.UTC))
                .setSubject("f1e33ab3-027f-47c5-bb07-8dd8ab37a2d3")
                .setExpiration(ZonedDateTime.now(ZoneOffset.UTC).plusMinutes(60));

        jwt.getOtherClaims().put("name", "Dan Moore");
        jwt.getOtherClaims().put("roles", new String[]{"admin"});

        // Sign and encode the JWT to a JSON string representation
        String encodedJWT = JWT.getEncoder().encode(jwt, signer);
        System.out.println(encodedJWT);

        // Todo API
        Verifier verifier = HMACVerifier.newVerifier("too many secrets");
        JWT decoded = JWT.getDecoder().decode(encodedJWT, verifier);

        System.out.println(decoded);

    }

If am doing something wrong let me know

wunmiji commented 12 months ago

Have done more research I understand how it work now.

mooreds commented 12 months ago

Awesome, glad you figured it out!