【问题标题】:Spring Oauth Get Current UserSpring Oauth 获取当前用户
【发布时间】:2019-02-02 04:44:38
【问题描述】:

我正在开发一个包含 3 个较小项目的系统,具体如下:

  • 一个客户
  • 资源服务器
  • 身份验证服务器

认证服务器有一个注册页面和一个登录页面。资源服务器由认证服务器保护。

我想从客户端通过 REST API 访问资源。客户端通过 OAuth2RestTemplate 从 Spring 调用资源服务器以访问资源。在我对自己进行身份验证后,我设法访问了该资源。

现在解决问题。在客户端,我需要知道当前用户以显示用户名并允许用户更改他的个人资料。

我尝试使用

通过 spring security 访问用户的主体
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

但它只是返回了null。 所以我的问题是:有没有办法让当前登录的用户使用OAuth2RestTemplate

编辑:

所以我决定改变计划,在我的身份验证服务器中实现一个链接,该链接返回用户信息。问题是,当我想通过OAuth2RestTemplate与身份验证服务器通话时,身份验证服务器只返回登录页面。当我从浏览器调用页面或想通过OAuth2RestTemplate 与资源服务器交谈时,一切正常。

【问题讨论】:

    标签: java spring oauth oauth-2.0 spring-oauth2


    【解决方案1】:

    在授权服务器中为您的 AuthorizationServerEndpointsConfigurer 设置一个 TokenEnhancer。您可以将用户信息作为附加信息映射添加到令牌中。

    这是一个自定义 TokenEnhancer 的示例实现,

        public class CustomTokenEnhancer implements TokenEnhancer {
    
        @Override
        public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
    
            final Map<String, Object> additionalInfo = new HashMap<String, Object>();
            UserDetails user = (UserDetails) authentication.getPrincipal();
    
            additionalInfo.put("<custom_user_info>", user.getUsername());
    
            ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
    
            return accessToken;
        }
    
    }
    

    在您的授权服务器中,

    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
            endpoints.tokenEnhancer(new CustomTokenEnhancer());
        }
    

    【讨论】:

    • 感谢您的回答,我试过了,但是在我添加了CustomTokenEnhancer 之后,我在客户端收到了一个AccessTokenRequiredException: OAuth2 access denied。我想这与身份验证服务器端的自动配置有关。我想我必须深入了解身份验证服务器端的配置。
    • 显示异常,它必须在你的授权服务器中
    【解决方案2】:

    通过覆盖类 AbstractAuthenticationProcessingFilter 的方法,在认证成功后将认证对象添加到安全上下文持有者

        public void successfulAuthentication(
        HttpServletRequest request,
        HttpServletResponse response,
                 FilterChain chain, 
                Authentication authentication) throws IOException, ServletException
    
                     {
                 // Add the authentication to the Security context 
       SecurityContextHolder
    .getContext()
    .setAuthentication(authentication); 
    
                }
    

    【讨论】:

      猜你喜欢
      • 2014-06-10
      • 2017-12-20
      • 2018-10-25
      • 2018-11-21
      • 2021-03-30
      • 2018-08-17
      • 1970-01-01
      • 2020-02-12
      • 1970-01-01
      相关资源
      最近更新 更多