Spring oauth2,使用访问令牌来检索用户数据?

时间:2018-01-24 03:17:21

标签: spring spring-security-oauth2

我使用spring security oauth2authorization_code类型。

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

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

但是,我无法找到教程,例子来说明我如何做到这一点......

1 个答案:

答案 0 :(得分:0)

你有两个选择。

  1. 通过添加额外声明添加令牌响应中的用户信息,请参阅can I include user information while issuing an access token?
  2. 实施userinfo端点
  3. @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;
        }
    
    }