Psy*_*nch 11 java spring spring-mvc spring-boot spring-oauth2
我有2个单独的Spring Boot应用程序,一个用作OAuth 2授权服务器,另一个用作资源服务器.我RemoteTokenServices
在资源服务器中使用Spring 来检查授权服务器中的令牌.现在,我正在尝试在资源服务器应用程序中定义受保护的控制器代码,但我不确定如何将UserDetails
类映射到通过OAuth 2机制提供的身份验证主体.
我已经使用自定义设置了我的授权服务器,该自定义TokenEnhancer
向令牌添加了更多详细信息,以便/oauth/check_token?token=<token>
返回自定义字段,我想将其映射到资源服务器控制器.
在更加单一的设置中,授权服务器也是资源服务器,我可以定义以这种方式使用经过身份验证的主体的控制器方法:
//User implements UserDetails
public Map<String, Object> getResource(@AuthenticationPrincipal User user) {
//code that uses the user object
}
Run Code Online (Sandbox Code Playgroud)
但是,在更加分散的方法中,这似乎并不直接.映射失败,user
参数最终成为空对象.我尝试使用以下方法:
public Map<String, Object> getResource(Authentication authentication) {
//code that uses the authentication object
}
Run Code Online (Sandbox Code Playgroud)
虽然上面的代码成功映射了身份验证详细信息,但它没有为我提供直接访问我通过TokenEnhancer
前面提到的设置的自定义字段的方法.我似乎无法从Spring文档中找到任何关于此的内容.
Psy*_*nch 21
要解决这个问题,请先介绍一下建筑背景.通过UserDetails
自动映射的对象@AuthenticationPrincipal
来自principal
活动Authentication
对象的字段.资源服务器控制器可以访问一个OAuth2Authencation
对象,该对象是Authentication
Spring OAuth2安全框架的专用实例,只需将其声明为方法参数的一部分即可.
public void controllerMethod(OAuth2Authentication authentication) {
//controller definition
}
Run Code Online (Sandbox Code Playgroud)
知道这一点,问题现在转移到如何确保对象中的getPrincipal()
方法Authentication
是我的自定义UserDetails
类的实例.将RemoteTokenServices
在资源服务器应用程序使用我的使用实例AccessTokenConverter
来解释该授权服务器发送令牌的详细信息.默认情况下,它使用,它只将DefaultAccessTokenConverter
身份验证主体设置为用户名,即String
.此转换器UserAuthenticationConverter
用于将来自授权服务器的数据转换为实例Authentication
.这是我需要定制的:
DefaultAccessTokenConverter tokenConverter = new DefaultAccessTokenConverter();
tokenConverter.setUserTokenConverter(new DefaultUserAuthenticationConverter() {
@Override
public Authentication extractAuthentication(Map<String, ?> map) {
Authentication authentication = super.extractAuthentication(map);
// User is my custom UserDetails class
User user = new User();
user.setSpecialKey(map.get("specialKey").toString());
return new UsernamePasswordAuthenticationToken(user,
authentication.getCredentials(), authentication.getAuthorities());
}
});
tokenServices.setAccessTokenConverter(tokenConverter);
Run Code Online (Sandbox Code Playgroud)
通过所有这些设置,该@AuthenticationPrincipal
机制现在可以按预期工作.
归档时间: |
|
查看次数: |
8448 次 |
最近记录: |