您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何将OAuth 2令牌映射到资源服务器中的UserDetails对象?

如何将OAuth 2令牌映射到资源服务器中的UserDetails对象?

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

其他 2022/1/1 18:19:31 有472人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶