0

I did API's using spring-boot and integrated Outh2 spring security. I have more API end points starting with /api/v1/ .I need to authenticate all the API except the API /api/v1/test-data.

My Resourceserver http config is as follows.

@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());
    } 

But .antMatchers("/api/v1/test-data").permitAll() is not working for me but .antMatchers("/api/v1/**").hasRole("API_ACCESS") is working for all endpoints coming under "/api/v1/".

My rest controllers are

@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);
    }

}

How to exclude "/api/v1/test-data" from "hasRole" outh check?

Exact Finder
  • 73
  • 2
  • 12
  • 3
    You disabled anonymous access but also want permitAll. I think there's a conflict here. – Vasan Feb 27 '18 at 19:17
  • 1
    @Vasan Syl's answer is correct, but this was the main issue i faced, and i got solution for that from https://stackoverflow.com/questions/30366405/how-to-disable-spring-security-for-particular-url..thanks – Exact Finder Feb 27 '18 at 19:45

1 Answers1

2

swap your rules:

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

The order matters.

Syl
  • 2,733
  • 2
  • 17
  • 20
  • 1
    Hi @Syl Thanks. all contrllers are correct , but as @ Vasan told there was a conflict between anonymous().disable() AND .permitAll(). And for that solution is there in https://stackoverflow.com/questions/30366405/how-to-disable-spring-security-for-particular-url – Exact Finder Feb 27 '18 at 19:47