我正在开发一个包含3个较小项目的系统,如下所示:
验证服务器具有寄存器和登录页面。资源服务器由身份验证服务器保护。
从客户端我想通过REST API访问资源。客户端通过Spring的OAuth2RestTemplate
调用资源服务器来访问资源。在我对自己进行身份验证后,我设法访问了该资源。
现在来问题了。在客户端,我需要知道当前用户显示用户名并使用户能够更改他的个人资料。
我试图通过spring security来访问用户的主体
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
但它刚刚返回null
。所以我的问题是:有没有办法用OAuth2RestTemplate
获取当前登录用户?
编辑:
所以我决定更改计划以在我的身份验证服务器中实现一个链接,该链接返回用户信息。问题是,当我想通过OAuth2RestTemplate
t认证服务器时,认证服务器只返回登录页面。当我从浏览器调用页面或当我想通过OAuth2RestTemplate
与资源服务器通信时,一切正常。
将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());
}
通过重写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);
}