Creating and Verifying JWT signature using public/private key in Spring boot security

15,967
  • 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;
}
Share:
15,967
user8363477
Author by

user8363477

Updated on June 11, 2022

Comments

  • user8363477
    user8363477 almost 2 years

    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