Spring Security自定义图形验证码过滤器

1.创建验证码相关的异常类ValidateCodeException

package com.mengxuegu.security.authentication.code;


import org.springframework.security.core.AuthenticationException;

/**
 * 验证码相关异常类
 */
public class ValidateCodeException extends AuthenticationException {

    public ValidateCodeException(String msg, Throwable t) {
        super(msg, t);
    }

    public ValidateCodeException(String msg) {
        super(msg);
    }
}

2.创建自定义图形验证码过滤器

package com.mengxuegu.security.authentication.code;

import com.mengxuegu.security.authentication.CustomAuthenticationFailureHandler;
import com.mengxuegu.security.controller.CustomLoginController;
import com.mengxuegu.security.properties.AuthenticationProperties;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component("imageCodeValidateFilter")
public class ImageCodeValidateFilter extends OncePerRequestFilter {

    @Autowired
    AuthenticationProperties authenticationProperties;

    @Autowired
    CustomAuthenticationFailureHandler customAuthenticationFailureHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest,
                                    HttpServletResponse httpServletResponse,
                                    FilterChain filterChain) throws ServletException, IOException {
        //1.如果是POST方式的登录请求,则校验输入的验证码是否正确
        if (authenticationProperties.getLoginProcessingUrl().equals(httpServletRequest.getRequestURI())
                &&httpServletRequest.getMethod().equalsIgnoreCase("post")){
            try {
                // 校验验证码合法性
                validate(httpServletRequest);
            }catch (AuthenticationException e){
                // 交给失败处理器进行处理异常
                customAuthenticationFailureHandler.onAuthenticationFailure(httpServletRequest,httpServletResponse,e);
                // 一定要记得结束
                return;
            }
        }
        // 放行请求
        filterChain.doFilter(httpServletRequest,httpServletResponse);
    }

    private void validate(HttpServletRequest httpServletRequest) {
        // 先获取session中的验证码
        String sessionCode = (String)httpServletRequest.getSession().getAttribute(CustomLoginController.SESSION_KEY);
        // 判断用户输入的验证码
        String inputCode = httpServletRequest.getParameter("code");
        // 判断是否正确
        if (StringUtils.isBlank(inputCode)){
            throw new ValidateCodeException("验证码不能为空");
        }
        if (!inputCode.equalsIgnoreCase(sessionCode)) {
            throw new ValidateCodeException("验证码输入错误");
        }
    }
}

3.SpringSecurityConfig

重点

http.addFilterBefore(imageCodeValidateFilter, UsernamePasswordAuthenticationFilter.class)
package com.mengxuegu.security.config;

import com.mengxuegu.security.authentication.code.ImageCodeValidateFilter;
import com.mengxuegu.security.properties.AuthenticationProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;


/**
 * alt+/ 导包
 * ctrl+o 覆盖
 *
 * @Auther: 梦学谷 www.mengxuegu.com
 */
@EnableWebSecurity // 开启springsecurity过滤链 filter
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {


    Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private AuthenticationProperties authenticationProperties;

    @Bean
    public PasswordEncoder passwordEncoder() {
        // 明文+随机盐值-》加密存储
        return new BCryptPasswordEncoder();
    }

    @Autowired
    UserDetailsService customUserDetailsService;

    @Autowired
    private AuthenticationSuccessHandler customAuthenticationSuccessHandler;

    @Autowired
    private AuthenticationFailureHandler customAuthenticationFailureHandler;

    @Autowired
    private ImageCodeValidateFilter imageCodeValidateFilter;

    /**
     * 认证管理器:
     * 1. 认证信息(用户名,密码)
     *
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        String password = passwordEncoder().encode("123456");
//        logger.info("加密之后存储的密码:"+password);
//        auth.inMemoryAuthentication().withUser("root").password(password).authorities("ADMIN");
        auth.userDetailsService(customUserDetailsService);
    }

    /**
     * 资源权限配置:
     * 1. 被拦截的资源
     *
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        System.out.println("用户认证");
//       http.httpBasic() // 采用 httpBasic认证方式
        http.addFilterBefore(imageCodeValidateFilter, UsernamePasswordAuthenticationFilter.class)
                .formLogin() // 表单登录方式
                .loginPage(authenticationProperties.getLoginPage())   //配置登录页面
                .loginProcessingUrl(authenticationProperties.getLoginProcessingUrl())  //登录表单提交处理url,默认是/login
                .usernameParameter(authenticationProperties.getUsernameParameter())
                .passwordParameter(authenticationProperties.getPasswordParameter())
                .successHandler(customAuthenticationSuccessHandler) // 认证成功处理器
                .failureHandler(customAuthenticationFailureHandler) // 认证失败处理器
                .and()
                .authorizeRequests() // 认证请求
                .antMatchers(authenticationProperties.getLoginPage(), "/code/image").permitAll()
                .anyRequest().authenticated() //所有访问该应用的http请求都要通过身份认证才可以访问
        ; // 注意不要少了分号
    }

    /**
     * 一般针对静态资源放行
     *
     * @param web
     */
    @Override
    public void configure(WebSecurity web) {
        web.ignoring().antMatchers(authenticationProperties.getStaticPaths());
    }
}
posted @ 2020-11-07 21:34  xl4ng  阅读(312)  评论(0编辑  收藏  举报