@SuppressWarnings("SpringJavaAutowiringInspection")
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private JwtAuthenticationEntryPoint unauthorizedHandler;
@Autowired
private UserDetailsService userDetailsService;
@Autowired
public void configureAuthentication(AuthenticationManagerBuilder
authenticationManagerBuilder) throws Exception {
authenticationManagerBuilder.userDetailsService(userDetailsService);
}
@Bean
public JwtAuthenticationTokenFilter authenticationTokenFilterBean() throws Exception {
return new JwtAuthenticationTokenFilter();
}
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
.csrf().disable()
.exceptionHandling()
.authenticationEntryPoint(unauthorizedHandler)
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/test").permitAll()
.antMatchers("/api/**").permitAll()
.anyRequest().authenticated();
httpSecurity.addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class);
}
}
I have a custom filter that runs before Spring Security. I want to be able to exclude some URLs (like /test
) from the filter and Spring Security and others to be intercepted (like /api/**
).
When using postman to test localhost/test
it still goes through the filter even though I have antMatchers("/test").permitAll()
.
How do I bypass the filter?
You can disable the Spring Security filter chain for some URLs, see WebSecurity#ignoring
:
Allows adding
RequestMatcher
instances that should that Spring Security should ignore. Web Security provided by Spring Security (including theSecurityContext
) will not be available onHttpServletRequest
that match. Typically the requests that are registered should be that of only static resources. For requests that are dynamic, consider mapping the request to allow all users instead.Example Usage:
webSecurityBuilder.ignoring() // ignore all URLs that start with /resources/ or /static/ .antMatchers("/resources/**", "/static/**");
Therefore, you can override WebSecurityConfigurerAdapter#configure
:
Override this method to configure
WebSecurity
. For example, if you wish to ignore certain requests.
To ignore path /test
you have to add following method to your configuration:
public void configure(WebSecurity web)
webSecurityBuilder
.ignoring()
.antMatchers("/test");
}
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