When configuring Filter in Java Configuration, it is convenient to inherit ʻorg.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter` and overwrite the two configure methods.
You can add a Filter for authentication with HttpSecurity and set WebSecurity to ignore the Filter.
SecurityConfig.java
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private static final String[] STATIC_RESOURCES = {
"/**/css/**", "/**/js/**", "/**/img/**",
};
@Override
protected void configure(HttpSecurity http) throws Exception {
//Add Filter to Security Filter Chain
http.addFilter(this.preAuthenticatedProcessingFilter());
}
@Override
public void configure(WebSecurity web) throws Exception {
//Set paths to exclude from the Security Filter Chain
web.ignoring().antMatchers(STATIC_RESOURCES);
}
//Filter registered in Security Filter Chain is not bean-defined
public AbstractPreAuthenticatedProcessingFilter preAuthenticatedProcessingFilter() throws Exception {
final SampleAuthFilter filter = new SampleAuthFilter();
filter.setAuthenticationManager(this.authenticationManager());
return filter;
}
}
There are many articles and sites of other people around here, so I don't have to bother to write it, but I've been addicted to it for a while, so I'll write it.
Even if you set ignore, Filter will be applied to all requests including static resources that do not require authentication. For a few days, I found some free time and searched for "spring security ignoring not work" etc., but I couldn't find a solution due to problems such as how to write the ignore settings.
When I think about it now, the comment here on StackOverflow was exactly the solution, but I didn't realize it.
The cause is that the Filter class was annotated with @Component
.
The same goes for adding @Bean
to the Configuration class.
As a result, it will be registered outside the Security Filter Chain.
The solution is, of course, not to register as a bean.
Some pages have sample code with @Bean
, so I thought some people would suffer from the same problem.
However, although it is unconfirmed, if you do not use Spring Boot (starter-web?), You may not get into this problem.
I got a hint from the solution to exclude from FilterRegistrationBean
on StackOverFlow and managed to solve it, but I can't seem to see it just by tracing from the source of WebSecurityConfigurerAdapter
.
How Spring Security works in Hello World was very helpful.
If I couldn't solve it in another day, the worst way "adding an if statement on the Filter side" was flickering (laughs).
Spring Security – security none, filters none, access permitAll Spring Security filter chain not ignoring specified path [duplicate] How Spring Security works in Hello World
Recommended Posts