小编典典
为了解决这个问题,让我先介绍一下建筑背景。通过进行UserDetails自动映射的对象@AuthenticationPrincipal来自principal活动Authentication对象的字段。资源服务器控制器仅通过将其声明为方法参数的一部分即可访问OAuth2Authencation对象,该对象是AuthenticationSpring
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 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机制现在可以按预期工作。
2020-05-30