我在尝试应用过滤器检查自定义UserDetails以确保用户在登录时完成一个过程时获得了太多的重定向。以下是我的配置和过滤器的内容:
@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);
}
}
这是我的过滤器:
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);
}
}
对于我出错的地方有任何帮助,我们将不胜感激。我已尝试在successHandler中注释掉我的重定向,但这也没有解决问题。
答案 0 :(得分:0)
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);
}
这解决了我的问题。