I am getting too many redirects while trying to apply a filter to check a custom UserDetails to make sure a user goes through a process while logging in. Here is what I have for my config and Filter:
@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true)
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
/*
* @Autowired public void configureGlobal(AuthenticationManagerBuilder auth)
* throws Exception {
* auth.inMemoryAuthentication().withUser("admin").password("admin").roles(
* "ADMIN", "USER").and().withUser("user") .password("user").roles("USER");
* }
*/
@Autowired
MySuccessHandler mySuccessHandler;
/*
* @Override public void configure(WebSecurity web) throws Exception {
* web.ignoring() // Spring Security should completely ignore URLs starting
* with /resources/ .antMatchers("/resources/**", "/webjars/**"); }
*/
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/resources/**", "/webjars/**", "/css/**", "/js/**", "/images/**");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().and().authorizeRequests().anyRequest().authenticated().and().formLogin().loginPage("/login")
.successHandler(mySuccessHandler).permitAll().and()
.addFilterBefore(new CustomFilter(), BasicAuthenticationFilter.class);
}
}
Here is my Filter:
public class CustomFilter extends GenericFilterBean {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
HttpSession session = req.getSession(false);
try {
SecurityContextImpl sci = (SecurityContextImpl) session.getAttribute("SPRING_SECURITY_CONTEXT");
MyUser myUser = (MyUser) sci.getAuthentication().getPrincipal();
if (myUser.isFirstLogin()) {
resp.sendRedirect("/hub/initial/landing");
}
} catch (NullPointerException e) {
}
filterChain.doFilter(request, response);
}
}
Any help on where I'm going wrong would be appreciated. I have tried commenting out my redirect in my successHandler and that did not solve the issue either.
boolean urlRequest = passwordURL.equals(req.getRequestURI());
MyUser myUser = (MyUser) sci.getAuthentication().getPrincipal();
if (myUser.isFirstLogin()) {
if (urlRequest) {
filterChain.doFilter(request, response);
} else
res.sendRedirect(passwordURL);
}
This solved the issue for me.