为了解决这个问题,让我先介绍一下建筑背景。通过进行UserDetails
自动映射的对象@AuthenticationPrincipal
来自principal
活动Authentication
对象的字段。资源服务器控制器仅通过将其声明为方法参数的一部分即可访问OAuth2Authencation
对象,该对象是Authentication
Spring OAuth2安全框架的专用实例。
public void controllerMethod(OAuth2Authentication authentication) {
//controller deFinition
}
知道了这一点,问题现在转移到如何确保对象中的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);
通过所有这些设置,该@AuthenticationPrincipal
机制现在可以按预期工作。