Spring Security permitAll()不匹配排除网址

时间:2018-02-27 18:16:15

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

我使用spring-boot和集成的Outh2弹簧安全性来做API。 我有更多以/ api / v1 /开头的API端点。我需要验证除API / api / v1 / test-data之外的所有API。

我的资源服务器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”?

1 个答案:

答案 0 :(得分:1)

交换你的规则:

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

订单很重要。