问题
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.
回答1:
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;
}
}
来源:https://stackoverflow.com/questions/39693017/how-can-i-get-a-custom-principal-object-with-spring-using-oauth2