Search code examples
springspring-security

@PreAuthorize(permitAll) still requires authentication


I have the following example method in my Repository (with @RepositoryRestResource annotation):

@Override
@PreAuthorize("permitAll")
@PostAuthorize("permitAll")
public Iterable<User> findAll();

But I'm still getting 401 Unauthorized, event when I add those permitAll annotation to whole Repository interface.

I got this as my WebSecurityConfigurerAdapter:

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Configuration
class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(final HttpSecurity http) throws Exception {
        http.authorizeRequests().anyRequest().fullyAuthenticated().and().httpBasic().and().csrf().disable();
    }
}

I suppose this takes precedence over those method annotations, bu I don't know how to fix this.


Solution

  • Method security is applied after the web security filter.

    Since you have anyRequest().fullyAuthenticated() in your configuration, your findAll method will never be hit. anyRequest().fullyAuthenticated() means that all attempts to access a web endpoint that does no have have some from of full user authentication on it will fail.

    From the JavaDoc

    Specify that URLs are allowed by users who have authenticated and were not "remembered".

    You will need to add an additional path in your web security, some like.

    protected void configure(final HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .anyRequest().fullyAuthenticated()
                .antMatchers(HttpMethod.GET, '/somePath').permitAll()
             .and()
                .httpBasic()
             .and()
                .csrf().disable();
    }