为了解决这个问题,让我先介绍一下建筑背景。通过进行
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<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机制现在可以按预期工作。



