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

简介: 阅读本文大概需要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图形化验证码的使用和介绍,小伙伴可以根据自己的需求进行引入。

相关文章
|
6天前
|
存储 弹性计算 安全
阿里云第七代云服务器ECS性能、适用场景与价格参考
阿里云第七代云服务器ECS(Elastic Compute Service)作为阿里云最新一代的高性能计算产品,凭借其基于最新硬件架构和虚拟化技术的全面升级,在计算能力、存储性能、网络传输速度以及灵活性等多个方面实现了显著提升。这一代云服务器旨在为用户提供更为强大、稳定且可定制的云端基础设施服务,广泛适用于从基础的Web托管到复杂的高性能计算等多种应用场景。
|
5天前
|
弹性计算 网络安全
阿里云国际OpenAPI多接口快速管理ECS服务器教程
阿里云国际OpenAPI多接口快速管理ECS服务器教程
|
3天前
|
弹性计算 开发框架 .NET
阿里云服务器购买教程及云服务器地域、实例、操作系统、带宽等参数选择指南
对于初次购买阿里云服务器的用户来说,想使用阿里云服务器搭建网站或者运行APP、小程序等项目,第一步就是要先购买阿里云服务器,下面小编以图文形式给大家介绍一下阿里云服务器的购买流程,以及购买过程中如何云服务器地域、实例、带宽等关键配置和选择这些参数的一些注意事项,以供参考。
|
6天前
|
域名解析 网络协议 数据安全/隐私保护
阿里云轻量应用服务器搭建WordPress个人博客教程
阿里云轻量应用服务器搭建WordPress个人博客教程
|
10天前
|
存储 机器学习/深度学习 应用服务中间件
阿里云倚天云服务器实例:计算型c8y、通用型g8y、内存型r8y实例介绍
阿里云倚天云服务器是基于阿里云自研的倚天710 ARM架构CPU打造的高性能计算产品系列,它依托先进的第四代神龙架构,旨在为用户提供稳定可预期的超高效能体验。倚天云服务器在存储、网络性能及计算稳定性方面实现了显著提升,主要得益于其芯片级的快速路径加速技术。本文将深度解析阿里云倚天云服务器的计算型c8y、通用型g8y、内存型r8y实例,探讨其优势及适用场景,以供选择参考。
|
11天前
|
网络协议 应用服务中间件 网络安全
阿里云轻量应用服务器的使用限制
阿里云轻量应用服务器的使用限制
|
13天前
阿里云国际版购买了服务器后如何下载发票?
阿里云国际版购买了服务器后如何下载发票?
|
13天前
|
弹性计算 安全 Linux
阿里云国际版ECS云服务器ping不通的原因分析
阿里云国际版ECS云服务器ping不通的原因分析
|
5天前
|
人工智能 运维 关系型数据库
携手UALink,阿里云磐久AI Infra 2.0服务器亮相2024 OCP全球峰会
阿里云服务器研发受邀和UALink联盟一起,在OCP全球峰会上重点阐述AI服务器Scale UP互连技术领域发展趋势