【问题标题】:Spring oauth2, Use access token to retrieve user data?Spring oauth2,使用访问令牌检索用户数据?
【发布时间】:2018-07-03 00:21:27
【问题描述】:

我正在使用spring security oauth2authorization_code 类型。

Oauth2 客户端成功为用户检索到access_token

现在,客户端需要使用access_token 检索电子邮件等用户信息。

但是我找不到教程,示例来说明我如何做到这一点..

【问题讨论】:

  • 您使用的是哪种类型的令牌?智威汤逊??您可以实现自己的 TokenEnhancer 以将自定义数据添加到该令牌。
  • 您通常可以在introspection endpoint 获取有关访问令牌的元数据。
  • oauth2 在 oauth/check_token 暴露了另一个端点。

标签: spring spring-security-oauth2


【解决方案1】:

你有两个选择。

  1. 通过添加额外声明在令牌响应中添加用户信息,请参阅can I include user information while issuing an access token?
  2. 实现用户信息端点

@RestController
@ProcessingController
@RequestMapping("/identity/userinfo")
public class UserInfoController {

    @RequestMapping(value = "", method = RequestMethod.GET)
    public ResponseEntity<?> userInfo(Principal principal,
                                      HttpServletRequest request) {
        return ResponseEntity.ok(principal);
    }

}

并确保您有一个配置为在该端点使用 oauth2 的 resourceServer

@Configuration
public class ResourceServerConfig {

    @Autowired
    private ResourceServerTokenServices defaultTokenServices;

    @Bean
    protected ResourceServerConfiguration identityResources() {

        ResourceServerConfiguration resource = new ResourceServerConfiguration() {
            // Switch off the Spring Boot @Autowired configurers
            public void setConfigurers(List<ResourceServerConfigurer> configurers) {
                super.setConfigurers(configurers);
            }
        };

        resource.setConfigurers(Arrays.asList(new ResourceServerConfigurerAdapter() {

            @Override
            public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
                resources.resourceId(ResourceId.IDENTITY_API.getName())
                        .tokenServices(defaultTokenServices);
            }

            @Override
            public void configure(HttpSecurity http) throws Exception {
                http
                        .requestMatchers()
                        .antMatchers("/identity/**")
                        .and()
                        .authorizeRequests()
                        .antMatchers("/identity/userinfo/**").hasAnyAuthority("ROLE_USER_INFO")
                        .anyRequest().authenticated();
            }
        }));
        resource.setOrder(3);
        return resource;
    }

}

【讨论】:

    猜你喜欢
    • 2018-05-06
    • 1970-01-01
    • 2019-10-25
    • 2017-08-03
    • 1970-01-01
    • 1970-01-01
    • 2019-02-14
    • 2015-04-12
    • 2017-08-31
    相关资源
    最近更新 更多