SpringSecurity+thymeleaf - 图片验证码校验

简介: 验证主要步骤:1、访问登录页面,页面浏览器,被设置Cookie。2、页面刷新图片验证码,渲染到页面。3、页面登录提交,一同提交用户输入的imgcode。4、根据配置,先校验验证码,在校验用户密码。5、如果校验不通过,跳转登录错误页面。

登录页面提交

<div class="form-group">
    <div class="pull-left">
        <img alt="Code" onclick="this.src='/verify'" src="/verify" />
    </div>
    <div class="pull-right">
        <input type="text" class="form-control" id="imgcode" name="imgcode" placeholder="Code">
    </div>
</div>

图片验证码过滤器

/**
 * 图片验证码过滤器。
 * @author yanghaitao
 */
@Component
public class ImageCodeFilter extends OncePerRequestFilter {
    /**
     * 日志输出工具
     */
    private final static Logger LOGGER = LoggerFactory.getLogger(ImageCodeFilter.class);
    
    /**
     * 只在登录时对验证码进行拦截,验证
     */
    private static final String url = "/login";
    
    /**
     * redis缓存数据
     */
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    
    /**
     * 页面种植图片验证码cookie
     */
    @Value("${server.servlet.session.cookie.imgname}")
    private String imgCookieName;
    
    /**
     * 路径匹配工具
     */
    private AntPathMatcher antPathMatcher = new AntPathMatcher();
    
    /**
     * 验证码拦截
     */
    @Override
    protected void doFilterInternal(
            HttpServletRequest request, 
            HttpServletResponse response, 
            FilterChain filterChain)
            throws ServletException, IOException {
        // 拦截登录请求
        String requestURI = request.getRequestURI();
        if(antPathMatcher.match(url, requestURI) && "POST".equals(request.getMethod())) {
            // 获取种植的cookie
            String cookieValue = IpUtils.getCookieValue(request, imgCookieName);
            LOGGER.info("verify cookieValue : {}", cookieValue);
            // 获取验证码
            String imgcode = request.getParameter("imgcode");
            LOGGER.info("verify imgcode : {}", imgcode);
            // 获取redis缓存的验证码
            String imgcodeRedis = redisTemplate.opsForValue().get(cookieValue);
            try {
                redisTemplate.delete(cookieValue);
            } catch (Exception e) { }
            LOGGER.info("verify imgcodeRedis : {}", imgcodeRedis);
            // 验证码校验
            if(imgcode == null || !imgcode.equalsIgnoreCase(imgcodeRedis)) {
                response.sendRedirect("/login?error");
                LOGGER.info("verify sendRedirect : {}", "/login?error");
                return;
            }
        }
        
        filterChain.doFilter(request, response);
    }
    
}

配置验证码过滤器

注意:图片验证码请求要和静态资源一样放行,不然页面无法访问

@Autowired
private ImageCodeFilter imageCodeFilter;

@Override
protected void configure(HttpSecurity http) throws Exception {
    LOGGER.info("SecurityConfig HttpSecurity ... ");
    http.addFilterBefore(imageCodeFilter, UsernamePasswordAuthenticationFilter.class)
        .authorizeRequests()
        .antMatchers("/assets/**", "/verify").permitAll() // 放行地址与静态资源地址
        .anyRequest().authenticated() // 其他地址军需验证
        .and()
        .formLogin()
        .loginPage("/login")
        .successHandler(new SuccessLoginHandler())
        .permitAll()
        .and()
        .logout()
        .invalidateHttpSession(true)
        .clearAuthentication(true)
        .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
        // .logoutSuccessHandler(new SuccessLogoutHandler())
        .logoutSuccessUrl("/login?logout")
        .permitAll()
        .and().csrf().disable();
}
相关文章
|
前端开发 PHP
ThinkPHP 验证码扩展库的使用,以及多应用模式下,如何自定义验证码校验规则
本文介绍了在ThinkPHP框架中使用验证码扩展库的方法,包括安装验证码扩展库、在页面中使用验证码、自定义验证码配置以及校验验证码的步骤和代码示例。
ThinkPHP 验证码扩展库的使用,以及多应用模式下,如何自定义验证码校验规则
|
SQL 前端开发 NoSQL
SpringBoot+Vue 实现图片验证码功能需求
这篇文章介绍了如何在SpringBoot+Vue项目中实现图片验证码功能,包括后端生成与校验验证码的方法以及前端展示验证码的实现步骤。
SpringBoot+Vue 实现图片验证码功能需求
|
C#
C# 图形验证码实现登录校验代码
C# 图形验证码实现登录校验代码
701 2
|
数据采集 自然语言处理 Python
用 Python 生成并识别图片验证码
用 Python 生成并识别图片验证码
602 1
|
缓存 NoSQL Java
案例 采用Springboot默认的缓存方案Simple在三层架构中完成一个手机验证码生成校验的程序
案例 采用Springboot默认的缓存方案Simple在三层架构中完成一个手机验证码生成校验的程序
415 5
|
前端开发 JavaScript 数据库
四. Django项目之电商购物商城 -- 图片验证码生成
四. Django项目之电商购物商城 -- 图片验证码生成
|
NoSQL Java Redis
认证服务---整合短信验证码,验证码倒计时,验证码防刷校验 【一】
这篇文章介绍了如何在分布式微服务项目中整合短信验证码服务,包括使用阿里云短信验证接口、将短信验证功能集成到第三方服务中、其他服务的远程调用,以及通过Redis实现验证码防刷机制的代码实现和遇到的问题解决方案。
【node】图片验证码(svg-captcha)
【node】图片验证码(svg-captcha)
831 0
|
数据采集 安全 前端开发
Java如何制作图片输入验证码
Java如何制作图片输入验证码
227 0