spring-security - 如何使用 OAuth2 通过 Spring 获取自定义 Principal 对象?

标签 spring-security spring-boot spring-oauth2

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

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

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

最佳答案

您可以通过设置 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;
    }
}

关于spring-security - 如何使用 OAuth2 通过 Spring 获取自定义 Principal 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39693017/

相关文章:

java - Spring BasicProcessingFilter 迁移到 Spring Security 4

java - Spring Boot jdbcAuthentication dataSource 未加载错误

spring - 将 .crt 添加到 Spring Boot 以启用 SSL

spring-boot - 在 spring-boot 中禁用特定 url 的 Keycloak 身份验证

java - Spring Kafka 客户端 SSL 设置

java - Spring SAML中指定IDP和SP的加密算法

Spring oauth2 hasRole 访问被拒绝

spring-security - 使用 Spring boot、Eureka、Zuul、Spring Oauth 创建 OAuth 安全微服务的问题

spring - 将 Spring 授权服务器连接到外部 IDP 并触发身份验证

spring - 如何在用户登录时设置 CORS