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.
The difference between @Secured and @PreAuthorize are as follows : The main difference between @Secured and @PreAuthorize is that @PreAuthorize can work with Spring EL. We can access methods and properties of SecurityExpressionRoot while using @PreAuthorize but not with @Secured.
Spring Security provides method level security using @PreAuthorize and @PostAuthorize annotations. This is expression-based access control. The @PreAuthorize can check for authorization before entering into method. The @PreAuthorize authorizes on the basis of role or the argument which is passed to the method.
Method-level security is implemented by placing the @PreAuthorize annotation on controller methods (actually one of a set of annotations available, but the most commonly used). This annotation contains a Spring Expression Language (SpEL) snippet that is assessed to determine if the request should be authenticated.
The global method security functionality is disabled by default. To enable it, you use the @EnableGlobalMethodSecurity annotation over the configuration class of your application. You can apply authorization rules that the application checks before the call to a method.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With