1

I don't know what I'm doing wrong, but when I try to secure some REST resources using a ResourceServerConfigurerAdapter it doesn't work. I can only accomplish my goal using @PreAuthorize or setting the security on the WebSecurityConfigurerAdapter.

Actually, the WebSecurityConfigurerAdapter is stealing all possibilities on HttpSecurity settings. I believe that it have something to do with filtering order. I searched for information on the documentation but found it quite vague. I know that on the Spring Boot version 1.5+ the filtering order of ResourceServerConfigurerAdapter has been changed, and I only managed to get it to work after setting a new order on the properties: security.oauth2.resource.filter-order=3

Being more specific, this code (on ResourceServerConfigurerAdapter) doesn't have any result:

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

It is only possible to protect "/api/hello" and "/api/me" annotating @PreAuthorize on the controller methods:

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

It is working, however, I fear that it could be done in a better way. Any ideas?

Tin Megali
  • 771
  • 5
  • 25

1 Answers1

1

After some digging, I found the solution. The problem is indeed related to the filtering order. The guys at Pivotal changed the Oauth2 Resource Filter Order, as you can see in this passage taken from Spring Boot 1.5 release note:

OAuth 2 Resource Filter

The default order of the OAuth2 resource filter has changed from 3 to SecurityProperties.ACCESS_OVERRIDE_ORDER - 1. This places it after the actuator endpoints but before the basic authentication filter chain. The default can be restored by setting security.oauth2.resource.filter-order = 3

However, as pointed by @ilovkatie on this thread, the order of the WebSecurityConfigurerAdapter was also changed to 100, taken precedence over ResourceServerConfigurerAdapter.

So, instead of changing ResourceServerConfigurerAdapter's order on properties, a more elegant solution would be to use @Order(SecurityProperties.ACCESS_OVERRIDE_ORDER) on WebSecurityConfigurerAdapter.

This will make the resources configuration take precedence over WebSecurityConfigurerAdapter and it will be possible to set security using HttpSecurity on the ResourceServerConfigurerAdapter, making unnecessary to use @PreAuthorize annotation.

Tin Megali
  • 771
  • 5
  • 25