我有一个
Spring Boot应用程序,它使用spring-security-jwt和spring-security-oath2.我有一个自定义User对象扩展UserDetails和一个Custom UserDetailsService从loadUserByUsername方法返回此对象.
但是当我使用Authentication对象的getPrincipal方法并尝试Cast到我的自定义用户对象时,它会失败,因为主体返回字符串vs我的自定义用户对象.
我的实际目标是在需要最多自定义对象详细信息的每个方法调用上消除持久层的行程.
最佳答案 您可以通过将AccessTokenConverter(间接保存UserDetailsService)设置为JwtAccessTokenConverter来完成此操作.请参阅accessTokenConverter()方法.
@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;
}
}