Spring Security 登录时如何获取其他参数(可用作校验验证码)

情景:在使用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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值