How to Create a JWT in Java with the secret base64 encoded

Using the online JWT debugger to encode and decode a JWT token I created this simple token
https://jwt.io/#debugger-io?token=eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJhZG1pbiIsImF1ZCI6IlNvbHIifQ.5T7L_L1MPfQ_5FjKGa1fTPqrzwK4bNSM812nW6oyjb8
The secret to encode the token is
qwertypassword

The header is { "alg": "HS256"}
The payload is { "sub": "admin", "aud": "Solr"}

When you encoded with the secret not base64 encoded, it generates the JWT
eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJhZG1pbiIsImF1ZCI6IlNvbHIifQ.5T7L_L1MPfQ_5FjKGa1fTPqrzwK4bNSM812nW6oyjb8

When the secret is base64 encoded it generates the JWT
eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJhZG1pbiIsImF1ZCI6IlNvbHIifQ.SWCJDd6B_m7xr_puQH-wgbxvXyJYXH9lTpldOU0eQKc

Here is the Java code to generate the JWT for when the secret is not base64 encoded.

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
public class JWTEncodeTest {
    public static void main(String[] args) {
        try {
            String secretkey="qwertypassword";

            //The JWT signature algorithm we will be using to sign the token
            String jwtToken = Jwts.builder()
                .setSubject("admin")
                .setAudience("Solr")
                .signWith(SignatureAlgorithm.HS256,secretkey.getBytes()).compact();

            System.out.println("jwtToken=");
            System.out.println(jwtToken);
        } catch (Exception e)
        {
            System.out.println(e.getMessage());
        }
    }
}

What am I missing in this Java code to generate the JWT with the secret base64 encoded to produce the JWT value of

eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJhZG1pbiIsImF1ZCI6IlNvbHIifQ.SWCJDd6B_m7xr_puQH-wgbxvXyJYXH9lTpldOU0eQKc

1 Like