I'm extending a WebSecurityConfigurerAdapter overriding the configure method. My goal is to place a filter on a specific URL that bypass the login page and make a manual authentication. To do that i need the filter to be executed only the first time the user try to reach the SECTION_WITH_FILTER url. That's my code:
@Autowired
MyFilter myFilter;
@Override
protected void configure(HttpSecurity http) throws Exception {
logger.debug("<CONFIGURE HTTPSECURITY/>");
http
.authorizeRequests()
.antMatchers("/login*.*", "/error.*", "/resources/**", "/javax**/**").permitAll()
.antMatchers("/SECTION_WITH_FILTER/**").permitAll()
.antMatchers("/", "/*.jsf", "/**/*.jsf", "/*.faces", "/**/*.faces").hasAnyRole("ADMIN")
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login.jsf")
.permitAll()
.and()
.logout()
.invalidateHttpSession(false)
.logoutSuccessUrl("/")
.deleteCookies("JSESSIONID")
.permitAll()
.and().csrf().disable();
http
.addFilterBefore(myFilter, BasicAuthenticationFilter.class);
}
My problem is that the filter starts after every submit in any form of the website.
I already tried with a FilterRegistrationBean used also for setting the filter only when the user goes to a specific URL:
@Bean
public FilterRegistrationBean filterRegistration() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(myFilter);
registration.addUrlPatterns("/SECTION_WITH_FILTER/**");
registration.setName("myFilter");
registration.setEnabled(true);
return registration;
}
But using this method a StackOverflowError exception is thrown.
org.apache.catalina.core.StandardWrapperValve invoke
GRAVE: Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Filter execution threw an exception] with root cause
java.lang.StackOverflowError
at javax.servlet.http.HttpServletRequestWrapper.getSession(HttpServletRequestWrapper.java:231)
at org.apache.catalina.core.ApplicationHttpRequest.getSession(ApplicationHttpRequest.java:589)
...
How can i change my code to make a filter specified for a single url that starts only the first time the user try to reach it? Thanks
You can implement the
OncePerRequestFilter, override thedoFilterInternalmethod to do your own business, and if some urls should not filter, you can override theshouldNotFiltermethod.this filter is used to identify that a request is already filtered. The default implementation is based on the configured name of the concrete filter instance.