情景:在使用Security时,在校验用户名,也就是在自定义的UserDetailsService类中loadUserByUsername方法只传入一个用户名参数,但需求往往可能携带多个参数校验,如何获取另外的参数,可以增加自定义的Security过滤器链来获取表单的其他参数或者校验验证码,并把自定义的过滤器链设置在security的UsernamePasswordAuthenticationFilter过滤器之前。
图解:
环境: IDEA版本2017.3.1 x64, JDK1.8, SpringBoot2.1.1, Druid1.1.8, mybatis1.3.2,Security5.1.2,thymeleaf3.0.11
总流程:
- 增加自定义的Security过滤器链,用来获取表单其他参数或者校验验证码
- 在项目中的SecurityConfig配置类中配置自定义的过滤器链在security验证用户之前
一、增加自定义的Security过滤器链,用来获取表单其他参数
- 此过滤器链是用来获取表单上的学校id参数
public class SchoolAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
//拦截的url
private String processUrl;
public SchoolAuthenticationFilter(String defaultFilterProcessesUrl, String failureUrl) {
super(defaultFilterProcessesUrl);
this.processUrl = defaultFilterProcessesUrl;
setAuthenticationFailureHandler(new SimpleUrlAuthenticationFailureHandler(failureUrl));
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res=(HttpServletResponse)response;
if(processUrl.equals(req.getServletPath()) && "POST".equalsIgnoreCase(req.getMethod())){
//获取表单的学校id参数
Integer schoolId = Integer.valueOf(req.getParameter("schoolId"));
//将学校id存入session
req.getSession().setAttribute("school",schoolId);
}
chain.doFilter(request, response);
}
@Override
public Authentication attemptAuthentication(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
throws AuthenticationException, IOException, ServletException {
return null;
}
}
由以上代码可以知道,已经获取了表单的学校id参数,同理,也可以在此过滤器做其他业务判断,例如校验验证码
二、在项目中的SecurityConfig配置类中配置自定义的过滤器链在security验证用户之前
@Override
protected void configure(HttpSecurity http) throws Exception {
// 禁用csrf防御机制(跨域请求伪造),这么做在测试和开发会比较方便。
http.csrf().disable();
//配置自定义过滤器在security的UsernamePasswordAuthenticationFilter过滤器之前
http.addFilterBefore(new SchoolAuthenticationFilter("/login", "/login?error"), UsernamePasswordAuthenticationFilter.class);
//开启记住我功能
http.rememberMe();
}
参考来源:https://blog.csdn.net/dushiwodecuo/article/details/78913113