如何使用 OAuth2 通过 Spring 获取自定义主体对象?

问题描述 投票:0回答:1

我有一个使用 spring-security-jwt 和 spring-security-oauth2 的 Spring Boot 应用程序。我有一个扩展 UserDetails 的自定义 User 对象和一个从 loadUserByUsername 方法返回该对象的 Custom UserDetailsService 。

但是,当我利用 Authentication 对象的 getPrincipal 方法并尝试转换为我的自定义用户对象时,它会失败,因为主体返回的是字符串而不是我的自定义用户对象。

我的实际目标是消除每个最需要自定义对象详细信息的方法调用中到持久层的行程。

spring-security spring-boot spring-oauth2
1个回答
3
投票

您可以通过将

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;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.