A JSON Web Key (JWK) represents a cryptographic key as JSON. In an OAuth 2 authorization server, a JWK supplies the signing key for JWT tokens: the server signs with a private key, and a resource server can obtain the public key to verify a token. section 8.2
For a Spring authorization server, generate a 2048-bit RSA key pair, wrap its keys in an RSAKey, and place it in a JWKSet. Expose that set through a JWKSource bean so the server can select the key when producing tokens. section 8.2
@Bean
public JWKSource<SecurityContext> jwkSource()
throws NoSuchAlgorithmException {
RSAKey rsaKey = generateRsa();
JWKSet jwkSet = new JWKSet(rsaKey);
return (jwkSelector, securityContext) -> jwkSelector.select(jwkSet);
}
private static RSAKey generateRsa() throws NoSuchAlgorithmException {
KeyPair keyPair = generateRsaKey();
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
return new RSAKey.Builder(publicKey)
.privateKey(privateKey)
.keyID(UUID.randomUUID().toString())
.build();
}
private static KeyPair generateRsaKey() throws NoSuchAlgorithmException {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048);
return keyPairGenerator.generateKeyPair();
}
@Bean
public JwtDecoder jwtDecoder(JWKSource<SecurityContext> jwkSource) {
return OAuth2AuthorizationServerConfiguration.jwtDecoder(jwkSource);
}
The configuration shows the JWKSource bean and the helper methods that generate and wrap the RSA key pair. section 8.2


