Spring Oauth获取当前用户

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

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

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

验证服务器具有寄存器和登录页面。资源服务器由身份验证服务器保护。

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

现在来问题了。在客户端,我需要知道当前用户显示用户名并使用户能够更改他的个人资料。

我试图通过spring security来访问用户的主体

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

但它刚刚返回null。所以我的问题是:有没有办法用OAuth2RestTemplate获取当前登录用户?

编辑:

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

java spring oauth oauth-2.0 spring-oauth2
2个回答
0
投票

将TokenEnhancer设置为Authorization server中的AuthorizationServerEndpointsConfigurer。您可以将用户信息添加到令牌作为附加信息映射。

以下是自定义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());
    }

0
投票

通过重写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); 

            }
© www.soinside.com 2019 - 2024. All rights reserved.