【问题标题】:Spring Security permitAll() not matching for exclude urls [duplicate]Spring Security permitAll()不匹配排除网址[重复]
【发布时间】:2018-08-07 11:51:58
【问题描述】:

我使用 spring-boot 和集成的 Outh2 spring security 做了 API。 我有更多以 /api/v1/ 开头的 API 端点。我需要对除 API /api/v1/test-data 之外的所有 API 进行身份验证。

我的 Resourcesserver http 配置如下。

@Override
    public void configure(HttpSecurity http) throws Exception {
       http.
                anonymous().disable()
                .authorizeRequests()
                .antMatchers("/api/v1/**").hasRole("API_ACCESS")
                .antMatchers("/api/v1/test-data").permitAll()
                .and().exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler());
    } 

.antMatchers("/api/v1/test-data").permitAll() 不适用于我,但.antMatchers("/api/v1/**").hasRole("API_ACCESS") 可用于“/api/v1/”下的所有端点。

我的休息控制器是

@RestController
@RequestMapping(path="/api/v1")
public class HotelController {

    @Autowired
    private HotelService service;
    @Autowired
    private APIAuthService authservice; 

    @GetMapping("/hotels")
    public ResponseEntity<Map<String,Object>> hotelsGet(@RequestParam(value = "page", defaultValue="1", required = false) Integer page, @RequestParam(value = "size", defaultValue="25", required = false) Integer size
            , @RequestParam(value = "orderby", defaultValue="hotelname", required = false) String orderby, @RequestParam(value = "order", defaultValue="asc", required = false) String order) {
        return this.service.list(page,size,orderby,order);
    }

    @GetMapping("/test-data")
    public String hotelsGetTest(@RequestParam(value = "page", defaultValue="1", required = false) Integer page, @RequestParam(value = "size", defaultValue="10", required = false) Integer size) {
        return "tested";
    }

    @GetMapping("/baseauth")
    public boolean baseauth(@RequestHeader(value = "authorization", required = true) String authString) {
        return this.authservice.isUserAuthenticated(authString);
    }

}

如何从“hasRole”outh check 中排除“/api/v1/test-data”?

【问题讨论】:

  • 您禁用了匿名访问,但还想要 permitAll。我认为这里有冲突。
  • @Vasan Syl 的回答是正确的,但这是我面临的主要问题,我从stackoverflow.com/questions/30366405/…得到了解决方案

标签: java spring spring-boot spring-security spring-security-oauth2


【解决方案1】:

交换你的规则:

            .antMatchers("/api/v1/test-data").permitAll()
            .antMatchers("/api/v1/**").hasRole("API_ACCESS")

顺序很重要。

【讨论】:

  • 嗨@Syl 谢谢。所有控制器都是正确的,但正如@Vasan 所说,anonymous().disable() 和 .permitAll() 之间存在冲突。对于该解决方案,stackoverflow.com/questions/30366405/…
猜你喜欢
  • 2018-08-12
  • 2019-03-10
  • 2016-02-16
  • 2019-09-27
  • 2018-09-08
  • 2018-01-31
  • 1970-01-01
  • 2017-08-20
  • 2021-09-23
相关资源
最近更新 更多