7
votes

I would like to know the process of creation and verification of JWT signature using public and private keys in spring boot security.

I am trying to validate JWT token using HMAC algorithm. I am building JWT with hardcoded secret "MYSECRET".

Jwts.builder()
                .setClaims(claims)
                .setSubject(subject)
                .setAudience(audience)
                .setIssuedAt(createdDate)
                .setExpiration(expirationDate)
                .signWith(SignatureAlgorithm.HS512, "MYSECRET")
                .compact()

For parsing the code is as follows

Jwts.parser()
                .setSigningKey("MYSECRET")
                .parseClaimsJws(token)
                .getBody();

Instead of using signing key as "MYSECRET", I would like to make use of public and private keys

1
Your code is not using spring security, it is using jjwt library, that can be used with spring or not. Alternatively spring has its own JWT implementation. Do you want to adapt your code to use a key pair or re-implement all? - pedrofb

1 Answers

10
votes
  • Generate JKS Java KeyStore File

Let’s first generate the keys – and more specifically a .jks file – using the command line tool keytool:

keytool -genkeypair -alias mytest -keyalg RSA -keypass mypass -keystore mytest.jks -storepass mypass

  • Export your public key

keytool -list -rfc --keystore mytest.jks | openssl x509 -inform pem -pubkey

Using your key to sign token in your Authorization Server.

@Bean
public JwtAccessTokenConverter accessTokenConverter(){

    JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
    KeyStoreKeyFactory keyStoreKeyFactory = 
      new KeyStoreKeyFactory(new ClassPathResource("mytest.jks"), "mypass".toCharArray());
    converter.setKeyPair(keyStoreKeyFactory.getKeyPair("mytest"));
    return converter;
}

Finally using your public key in your resource server.

@Bean
public JwtAccessTokenConverter accessTokenConverter() {
    JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
    Resource resource = new ClassPathResource("public.txt");
    String publicKey = null;
    try {
        publicKey = IOUtils.toString(resource.getInputStream());
    } catch (final IOException e) {
        throw new RuntimeException(e);
    }
    converter.setVerifierKey(publicKey);
    return converter;
}