【问题标题】:How to get all authority of authenticated user in OAuth2 Resource server如何在 OAuth2 资源服务器中获得经过身份验证的用户的所有权限
【发布时间】:2019-08-08 16:14:08
【问题描述】:

有一个资源服务器,配置如下:

@SpringBootApplication
@RestController
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class ResourceServer extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(ResourceServer.class);
    }

    public static void main(String[] args) {
        SpringApplication.run(ResourceServer.class, args);
    }


    //@PreAuthorize("hasRole('ROLE_USER')")
    @RequestMapping(value = "/user", method = RequestMethod.GET)
    public Map<String, String> user(Principal user) {

        OAuth2Authentication oAuth2Authentication = (OAuth2Authentication) SecurityContextHolder.getContext().getAuthentication();
        Authentication userAuthentication = oAuth2Authentication.getUserAuthentication();
        return (Map<String, String>) userAuthentication.getDetails();

    }

}

@Configuration
@EnableResourceServer
public class ResourcesServerConfiguration extends ResourceServerConfigurerAdapter {
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers(HttpMethod.GET, "/api/**").access("#oauth2.hasScope('read')");
    }

    @Primary
    @Bean
    public RemoteTokenServices tokenService() {
        RemoteTokenServices tokenService = new RemoteTokenServices();
        tokenService.setCheckTokenEndpointUrl("http://localhost:8081/auth/account/getDetailUser");
        tokenService.setClientId("web");
        tokenService.setClientSecret("secret");
        return tokenService;
    }
}

它的application.yml是:

spring:
    datasource:
        url: jdbc:oracle:thin:@192.168.192.131:1521:hamed
        hikari:
            connection-test-query: SELECT 1 FROM DUAL
            minimum-idle: 1
            maximum-pool-size: 5
        driver-class-name: oracle.jdbc.OracleDriver
        username: test
        password: test
        initialization-mode: always
    jpa:
      hibernate:
        ddl-auto: none
      database-platform: org.hibernate.dialect.Oracle12cDialect
logging:
  level:
    org.springframework.security: DEBUG

server:
  port: 8083
  context-path: /micro1
security:
  basic:
    enabled: false
  oauth2:
    client:
      clientId: web
      clientSecret: secret
      accessTokenUri: http://localhost:8081/auth/oauth/token
      userAuthorizationUri: http://localhost:8081/auth/oauth/authorize
    resource:
      userInfoUri: http://localhost:8081/auth/account/getDetailUser

需要说明的是,流程是Authorization_code,在UAA中带有JDBC token store,spring boot的版本是1.5.8.RELEASE
用户被重定向到 UAA 并成功登录,并被重定向到带有代码的客户端。到目前为止,一切都很好,但是当我请求资源服务器时,我想像这样获得经过身份验证的用户的所有权限:

@RequestMapping(value = "/user", method = RequestMethod.GET)
    public Map<String, String> user(Principal user) {

        OAuth2Authentication oAuth2Authentication = (OAuth2Authentication) SecurityContextHolder.getContext().getAuthentication();
        Authentication userAuthentication = oAuth2Authentication.getUserAuthentication();
        return (Map<String, String>) userAuthentication.getDetails();

    }

引发以下异常:

java.lang.ClassCastException: org.springframework.security.authentication.AnonymousAuthenticationToken 不能转换为 org.springframework.security.oauth2.provider.OAuth2Authentication

资源服务器哪里出错,丢失了什么配置?

【问题讨论】:

    标签: spring-boot oauth-2.0 spring-security-oauth2


    【解决方案1】:

    你可以使用这样的代码

    @GetMapping({"/user", "/me"})
    public Map<String, Object> user(Principal principal){
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("name", principal.getName());
        if( principal instanceof OAuth2Authentication) {
            OAuth2Authentication oauth = (OAuth2Authentication)principal;
            map.put("authorities",oauth.getUserAuthentication().getAuthorities()
                                   .stream()
                                   .map(GrantedAuthority::getAuthority)
                                   .collect(Collectors.toList()));
        }
        return map;
    }
    

    【讨论】:

      猜你喜欢
      • 2010-09-21
      • 1970-01-01
      • 2010-10-07
      • 2021-10-14
      • 2016-12-04
      • 1970-01-01
      • 2017-11-05
      • 2017-04-05
      • 2020-04-09
      相关资源
      最近更新 更多