Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get a custom Principal object with Spring using OAuth2?

I have a Spring Boot application utilizing spring-security-jwt and spring-security-oauth2. I've got a custom User object extending UserDetails and a Custom UserDetailsService returning this object from the loadUserByUsername method.

But when I utilize the getPrincipal method of the Authentication object and try to Cast to my custom user object, it fails as the principal is returning a string vs my custom user object.

My actual goal is to eliminate the trip to the persistence layer on every method call that requires the custom object detail which is most.

like image 835
Jim Hankins Avatar asked Oct 19 '22 01:10

Jim Hankins


1 Answers

You can do this by setting an AccessTokenConverter (which indirectly holds your UserDetailsService) to JwtAccessTokenConverter. See accessTokenConverter() method.

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    // Other configurations omitted

    @Autowired
    private AuthenticationManager authenticationManager;

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

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

    @Bean
    public JwtAccessTokenConverter accessTokenConverter() {
        DefaultUserAuthenticationConverter duac = new DefaultUserAuthenticationConverter();
        duac.setUserDetailsService(userDetailsService);

        DefaultAccessTokenConverter datc = new DefaultAccessTokenConverter();
        datc.setUserTokenConverter(duac);

        JwtAccessTokenConverter jatc = new JwtAccessTokenConverter();
        jatc.setAccessTokenConverter(datc); // IMPORTANT
        jatc.setSigningKey("your-signing-key");
        return jatc;
    }

    @Bean
    public DefaultTokenServices tokenServices() {
        DefaultTokenServices tokenServices = new DefaultTokenServices();
        tokenServices.setTokenStore(tokenStore());
        tokenServices.setSupportRefreshToken(true);
        return tokenServices;
    }
}
like image 149
Minglei Lee Avatar answered Nov 15 '22 09:11

Minglei Lee