【发布时间】:2017-11-23 06:07:45
【问题描述】:
我不知道我做错了什么,但是当我尝试使用 ResourceServerConfigurerAdapter 保护一些 REST 资源时它不起作用。我只能使用@PreAuthorize 或在WebSecurityConfigurerAdapter 上设置安全性来实现我的目标。
实际上,WebSecurityConfigurerAdapter 正在窃取HttpSecurity 设置的所有可能性。我相信它与过滤顺序有关。我搜索了有关文档的信息,但发现它很模糊。我知道在 Spring Boot 版本 1.5+ 上,ResourceServerConfigurerAdapter 的过滤顺序已更改,我只有在属性上设置新顺序后才能使其工作:security.oauth2.resource.filter-order=3
更具体地说,这段代码(ResourceServerConfigurerAdapter)没有任何结果:
@Override
public void configure(HttpSecurity http) throws Exception {
http.requestMatcher(new OAuthRequestedMatcher())
.anonymous().disable()
.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS).permitAll()
.antMatchers("/api/hello").access("hasAnyRole('USER')")
.antMatchers("/api/me").hasAnyRole("USER", "ADMIN");
}
只能在控制器方法上保护"/api/hello"和"/api/me"注释@PreAuthorize:
@PreAuthorize("hasAnyRole('USER','ADMIN')")
@GetMapping("/api/hello")
public ResponseEntity<?> hello() {
String name = SecurityContextHolder.getContext().getAuthentication().getName();
String msg = String.format("Hello %s", name);
return new ResponseEntity<Object>(msg, HttpStatus.OK);
}
它正在工作,但是,我担心它可以以更好的方式完成。有什么想法吗?
【问题讨论】:
标签: spring spring-boot spring-security spring-security-oauth2