Spring Security exclude url patterns in security annotation configurartion
Solution 1:
Found the solution in Spring security examples posted in Github.
WebSecurityConfigurerAdapter
has a overloaded configure
message that takes WebSecurity
as argument which accepts ant matchers on requests to be ignored.
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/authFailure");
}
See Spring Security Samples for more details
Solution 2:
Where are you configuring your authenticated URL pattern(s)? I only see one uri in your code.
Do you have multiple configure(HttpSecurity) methods or just one? It looks like you need all your URIs in the one method.
I have a site which requires authentication to access everything so I want to protect /*. However in order to authenticate I obviously want to not protect /login. I also have static assets I'd like to allow access to (so I can make the login page pretty) and a healthcheck page that shouldn't require auth.
In addition I have a resource, /admin, which requires higher privledges than the rest of the site.
The following is working for me.
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/login**").permitAll()
.antMatchers("/healthcheck**").permitAll()
.antMatchers("/static/**").permitAll()
.antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
.antMatchers("/**").access("hasRole('ROLE_USER')")
.and()
.formLogin().loginPage("/login").failureUrl("/login?error")
.usernameParameter("username").passwordParameter("password")
.and()
.logout().logoutSuccessUrl("/login?logout")
.and()
.exceptionHandling().accessDeniedPage("/403")
.and()
.csrf();
}
NOTE: This is a first match wins so you may need to play with the order. For example, I originally had /** first:
.antMatchers("/**").access("hasRole('ROLE_USER')")
.antMatchers("/login**").permitAll()
.antMatchers("/healthcheck**").permitAll()
Which caused the site to continually redirect all requests for /login back to /login. Likewise I had /admin/** last:
.antMatchers("/**").access("hasRole('ROLE_USER')")
.antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
Which resulted in my unprivledged test user "guest" having access to the admin interface (yikes!)
Solution 3:
When you say adding antMatchers doesnt help - what do you mean? antMatchers is exactly how you do it. Something like the following should work (obviously changing your URL appropriately):
@Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/authFailure").permitAll()
.antMatchers("/resources/**").permitAll()
.anyRequest().authenticated()
If you are still not having any joy, then you will need to provide more details/stacktrace etc.
Details of XML to Java config switch is here