Search code examples
javaspringspring-securityspring-security-oauth2jjwt

Java - How to use HS256 with JwtAccessTokenConverter


I am currently following this tutorial on how to implement oauth2 Authentication and Authorization with microservices:

http://stytex.de/blog/2016/02/01/spring-cloud-security-with-oauth2/

I have it working as is, but I am having a real hard time trying to figure out how to implement jwt with HS256 rather than the current RSA256 algorithm that's being used.

I think I've narrowed it down to this snippet of code from the authentication server in the Oauth2Configuration class:

 @Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
    endpoints.tokenStore(tokenStore()).tokenEnhancer(jwtTokenEnhancer()).authenticationManager(authenticationManager);
}

@Autowired
@Qualifier("authenticationManagerBean")
private AuthenticationManager authenticationManager;

@Bean
public TokenStore tokenStore() {
    return new JwtTokenStore(jwtTokenEnhancer());
}




@Bean
protected JwtAccessTokenConverter jwtTokenEnhancer() {
    KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(new ClassPathResource("jwt.jks"), "mySecretKey".toCharArray());
    JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
    converter.setKeyPair(keyStoreKeyFactory.getKeyPair("jwt"));

    return converter;
}

More specifically, I believe I'd have to change some things with the jwtTokenEnhancer method.

I've looked at documentation and I have not seen anything related to HS256 so any sort of clarification would be greatly appreciated.


Solution

  • You are configuring your JwtAccessTokenConverter to use a key pair therefore it will use RSA. If you want to setSigningKey it will use HMACSHA256.

    Take a look at the code :

    public void setSigningKey(String key) {
        Assert.hasText(key);
        key = key.trim();
    
        this.signingKey = key;
    
        if (isPublic(key)) {
            signer = new RsaSigner(key);
            logger.info("Configured with RSA signing key");
        }
        else {
            // Assume it's a MAC key
            this.verifierKey = key;
            signer = new MacSigner(key);
        }
    }
    

    You can see if the format is not RSA then a MacSigner is used and MacSigner implements HMACSHA256