【服务器开发系列】图形验证码到底是怎么回事?

简介: 阅读本文大概需要10分钟。

1什么是验证码?


验证码是一种区分用户是计算机还是人的公共全自动程序。短时间是无法退出人类舞台的,目前只是尽量提升用户体验


作用


  • 账号安全
  • 反作弊
  • 反爬虫
  • 防论坛灌水
  • 防恶意注册


分类


  • 图形验证码
  • Gif动画验证码
  • 手机短信验证码
  • 手机语音验证码
  • 视频验证码
  • web2.0验证码


2kaptcha验证码组件


kaptcha 是一个非常实用的验证码生成工具;有了它,你可以生成各种样式的验证码,因为它是可配置的


常见配置


  1. 验证码的字体
  2. 验证码字体的大小
  3. 验证码字体的字体颜色
  4. 验证码内容的范围(数字,字母,中文汉字)
  5. 验证码图片的大小,边框,边框粗细,边框颜色
  6. 验证码的干扰线(可以自己继承com.google.code.kaptcha.NoiseProducer写一个自定义的干扰线)
  7. 验证码的样式(鱼眼样式、3D、普通模糊……当然也可以继承com.google.code.kaptcha.GimpyEngine自定义样式)


引入maven配置



<dependency>
    <groupId>com.github.axet</groupId>
    <artifactId>kaptcha</artifactId>
    <version>0.0.9</version>
</dependency>



  kaptcha.properties


kaptcha.textproducer.font.color=red
kaptcha.image.width=130
kaptcha.image.height=44
kaptcha.textproducer.font.size=35
kaptcha.textproducer.char.length=4
kaptcha.textproducer.font.names=\\u5B8B\\u4F53,\\u6977\\u4F53,\\u5FAE\\u8F6F\\u96C5\\u9ED1
kaptcha.noise.color=gray
kaptcha.obscurificator.impl=com.google.code.kaptcha.impl.WaterRipple


用filter过滤器来生成验证码,具体步骤如下:


1、web.xml


<filter>
    <filter-name>KaptchaFilter</filter-name>
    <filter-class>com.xxoo.admin.ui.filter.KaptchaFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>KaptchaFilter</filter-name>
    <url-pattern>/kaptcha.jpg</url-pattern>
</filter-mapping>


说明:验证码过滤器需要放到Shiro之后,因为Shiro将包装HttpSession.如果不,可能造成两次的sesisonid不一样。


2、图片验证码类


public class CaptchaService {
    private static ImageCaptchaService instance = null;
    static {
        instance = new KaptchaImageCaptchaService();
    }
    public synchronized static ImageCaptchaService getInstance() {
        return instance;
    }
    public synchronized static boolean validate(HttpServletRequest httpServletRequest, String input) throws Exception {
        String text = instance.getText(httpServletRequest);
        boolean result = text.equalsIgnoreCase(input);
        instance.removeKaptcha(httpServletRequest);
        return result;
    }
}


3、基于Kaptcha的验证码图片实现


public class KaptchaImageCaptchaService implements ImageCaptchaService {
    private Logger logger = LoggerFactory.getLogger(getClass());
    public KaptchaImageCaptchaService() {
    }
    public static Config getConfig() throws IOException {
        Properties p = new Properties();
        p.load(new DefaultResourceLoader().getResource("kaptcha.properties").getInputStream());
        Config config = new Config(p);
        return config;
    }
    @Override
    public void create(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        httpServletResponse.setDateHeader("Expires", 0L);
        httpServletResponse.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        httpServletResponse.addHeader("Cache-Control", "post-check=0, pre-check=0");
        httpServletResponse.setHeader("Pragma", "no-cache");
        httpServletResponse.setContentType("image/jpeg");
        Config config = getConfig();
        Producer producer = config.getProducerImpl();
        String capText = producer.createText();
        if(logger.isDebugEnabled()){
            logger.info("create captcha:" + capText + ":" + config.getSessionKey() );
        }
        httpServletRequest.getSession().setAttribute(config.getSessionKey(), capText);
        httpServletRequest.getSession().setAttribute(config.getSessionDate(), new Date());
        BufferedImage bi = producer.createImage(capText);
        ServletOutputStream out = httpServletResponse.getOutputStream();
        ImageIO.write(bi, "jpg", out);
        out.flush();
        out.close();
    }
    @Override
    public String getText(HttpServletRequest httpServletRequest) throws Exception {
        return (String)httpServletRequest.getSession().getAttribute(getConfig().getSessionKey());
    }
    @Override
    public void removeKaptcha(HttpServletRequest httpServletRequest) throws Exception {
        httpServletRequest.getSession().removeAttribute(getConfig().getSessionKey());
        httpServletRequest.getSession().removeAttribute(getConfig().getSessionDate());
    }
}


4、验证码工具类


public class CaptchaService {
    private static ImageCaptchaService instance = null;
    static {
        instance = new KaptchaImageCaptchaService();
    }
    public synchronized static ImageCaptchaService getInstance() {
        return instance;
    }
    public synchronized static boolean validate(HttpServletRequest httpServletRequest, String input) throws Exception {
        String text = instance.getText(httpServletRequest);
        boolean result = text.equalsIgnoreCase(input);
        instance.removeKaptcha(httpServletRequest);
        return result;
    }
}


5、生成验证码过滤器


public class KaptchaFilter extends OncePerRequestFilter {
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        try {
            CaptchaService.getInstance().create(httpServletRequest,httpServletResponse);
        } catch (Exception e) {
            logger.info("create captcha error.",e);
        }
    }
}


6、验证码校验


private boolean doCaptchaValidate(HttpServletRequest request, String code) {
        //比对
        try {
            if (code == null || !CaptchaService.validate(request, code)) {
                return false;
            } else {
                return true;
            }
        } catch (Exception e) {
            logger.warn("captcha check error!");
            return false;
        }
}


总结


本文主要讲述了kaptcha图形化验证码的使用和介绍,小伙伴可以根据自己的需求进行引入。

相关文章
|
1月前
|
机器学习/深度学习 编解码 人工智能
阿里云gpu云服务器租用价格:最新收费标准与活动价格及热门实例解析
随着人工智能、大数据和深度学习等领域的快速发展,GPU服务器的需求日益增长。阿里云的GPU服务器凭借强大的计算能力和灵活的资源配置,成为众多用户的首选。很多用户比较关心gpu云服务器的收费标准与活动价格情况,目前计算型gn6v实例云服务器一周价格为2138.27元/1周起,月付价格为3830.00元/1个月起;计算型gn7i实例云服务器一周价格为1793.30元/1周起,月付价格为3213.99元/1个月起;计算型 gn6i实例云服务器一周价格为942.11元/1周起,月付价格为1694.00元/1个月起。本文为大家整理汇总了gpu云服务器的最新收费标准与活动价格情况,以供参考。
阿里云gpu云服务器租用价格:最新收费标准与活动价格及热门实例解析
|
18天前
|
Cloud Native Java 编译器
将基于x86架构平台的应用迁移到阿里云倚天实例云服务器参考
随着云计算技术的不断发展,云服务商们不断推出高性能、高可用的云服务器实例,以满足企业日益增长的计算需求。阿里云推出的倚天实例,凭借其基于ARM架构的倚天710处理器,提供了卓越的计算能力和能效比,特别适用于云原生、高性能计算等场景。然而,有的用户需要将传统基于x86平台的应用迁移到倚天实例上,本文将介绍如何将基于x86架构平台的应用迁移到阿里云倚天实例的服务器上,帮助开发者和企业用户顺利完成迁移工作,享受更高效、更经济的云服务。
将基于x86架构平台的应用迁移到阿里云倚天实例云服务器参考
|
16天前
|
编解码 前端开发 安全
通过阿里云的活动购买云服务器时如何选择实例、带宽、云盘
在我们选购阿里云服务器的过程中,不管是新用户还是老用户通常都是通过阿里云的活动去买了,一是价格更加实惠,二是活动中的云服务器配置比较丰富,足可以满足大部分用户的需求,但是面对琳琅满目的云服务器实例、带宽和云盘选项,如何选择更适合自己,成为许多用户比较关注的问题。本文将介绍如何在阿里云的活动中选择合适的云服务器实例、带宽和云盘,以供参考和选择。
通过阿里云的活动购买云服务器时如何选择实例、带宽、云盘
|
14天前
|
弹性计算 运维 安全
阿里云轻量应用服务器和经济型e实例区别及选择参考
目前在阿里云的活动中,轻量应用服务器2核2G3M带宽价格为82元1年,2核2G3M带宽的经济型e实例云服务器价格99元1年,对于云服务器配置和性能要求不是很高的阿里云用户来说,这两款服务器配置和价格都差不多,阿里云轻量应用服务器和ECS云服务器让用户二选一,很多用户不清楚如何选择,本文来说说轻量应用服务器和经济型e实例的区别及选择参考。
阿里云轻量应用服务器和经济型e实例区别及选择参考
|
15天前
|
机器学习/深度学习 存储 人工智能
阿里云GPU云服务器实例规格gn6v、gn7i、gn6i实例性能及区别和选择参考
阿里云的GPU云服务器产品线在深度学习、科学计算、图形渲染等多个领域展现出强大的计算能力和广泛的应用价值。本文将详细介绍阿里云GPU云服务器中的gn6v、gn7i、gn6i三个实例规格族的性能特点、区别及选择参考,帮助用户根据自身需求选择合适的GPU云服务器实例。
阿里云GPU云服务器实例规格gn6v、gn7i、gn6i实例性能及区别和选择参考
|
8天前
|
弹性计算 人工智能 安全
阿里云推出第九代ECS实例,最高提升30%性能
阿里云推出第九代ECS实例,最高提升30%性能
|
25天前
|
存储 弹性计算 运维
阿里云日常运维-购买服务器
这篇文章是关于如何在阿里云购买和配置云服务器ECS的教程。
59 6
阿里云日常运维-购买服务器
|
17天前
|
弹性计算
阿里云美国服务器需要备案吗?必看!
阿里云美国服务器无需ICP备案,适用于希望避开备案流程的用户。不同于中国大陆地区服务器,美国服务器及中国香港服务器均无需备案。用户可直接解析域名使用。阿里云提供美国云服务器ECS与轻量应用服务器两种选择,分别满足不同需求
71 9
|
9天前
|
人工智能 运维 Cloud Native
专访阿里云:AI 时代服务器操作系统洗牌在即,生态合作重构未来
AI智算时代,服务器操作系统面临的挑战与机遇有哪些?
专访阿里云:AI 时代服务器操作系统洗牌在即,生态合作重构未来

热门文章

最新文章