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

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

相关文章
|
29天前
|
存储 缓存 数据挖掘
阿里云目前最便宜云服务器介绍:38元、99元、199元性能,选购攻略参考
轻量应用服务器2核2G峰值200M带宽38元1年;云服务器经济型e实例2核2G3M带宽99元1年;云服务器通用算力型u1实例2核4G5M带宽199元1年。对于还未使用过阿里云服务器的用户来说,大家也不免有些疑虑,这些云服务器性能究竟如何?它们适用于哪些场景?能否满足自己的使用需求呢?接下来,本文将为您全方位介绍这几款云服务器,以供您了解及选择参考。
|
2月前
|
网络安全 云计算
如何设置阿里云轻量应用服务器镜像?
本文介绍了在阿里云轻量应用服务器上创建与配置镜像的详细步骤。镜像是一种特殊的文件系统映射,可用于快速克隆服务器配置。内容涵盖准备条件、登录控制台、创建实例、生成镜像、下载与设置镜像,以及如何使用镜像启动新实例。适合希望提升服务器部署效率的用户参考。
|
2月前
|
存储 弹性计算 安全
阿里云轻量服务器通用型、CPU优化型、多公网IP型、国际型、容量型不同实例区别与选择参考
阿里云轻量应用服务器实例类型分为通用型、CPU优化型、多公网IP型、国际型、容量型,不同规格族的适用场景和特点不同,收费标准也不一样。本文为大家介绍轻量应用服务器通用型、多公网IP型、容量型有何区别?以及选择参考。
|
13天前
|
弹性计算 Devops Shell
用阿里云 DevOps Flow 实现 ECS 部署自动化:从准备到落地的完整指南
阿里云 DevOps Flow 是一款助力开发者实现自动化部署的高效工具,支持代码流水线构建、测试与部署至ECS实例,显著提升交付效率与稳定性。本文详解如何通过 Flow 自动部署 Bash 脚本至 ECS,涵盖环境准备、流水线搭建、源码接入、部署流程设计及结果验证,助你快速上手云上自动化运维。
62 0
|
2月前
|
弹性计算 编解码 大数据
性价比最高提升50%!阿里云企业级云服务器上新
阿里云ECS云服务器推出全新升级的u2系列实例,包括基于Intel的u2i实例与首个基于AMD的u2a实例,提供企业级独享算力,综合性价比最高提升50%。u2i实例已开放公测,适用于中小型数据库、企业网站建设等场景。同时发布基于AMD的第九代旗舰实例g9ae,性能提升65%,适用于大数据、视频转码等密集型业务。
208 0
|
21天前
|
存储 域名解析 弹性计算
阿里云上云流程参考:云服务器+域名+备案+域名解析绑定,全流程图文详解
对于初次通过阿里云完成上云的企业和个人用户来说,很多用户不仅是需要选购云服务器,同时还需要注册域名以及完成备案和域名的解析相关流程,从而实现网站的上线。本文将以上云操作流程为核心,结合阿里云的活动政策与用户系统梳理云服务器选购、域名注册、备案申请及域名绑定四大关键环节,以供用户完成线上业务部署做出参考。
|
27天前
|
存储 弹性计算 固态存储
阿里云云服务器配置攻略
选择云服务器需结合业务需求、访问量、ECS实例规格、存储类型与带宽等因素。个人用户可选轻量服务器,企业应用需更高配置,如通用型或内存型实例。带宽根据流量选择,支持按固定或使用量计费。存储方面,系统盘可选小容量,数据盘按需配置,I/O敏感业务建议SSD或ESSD云盘。
|
2月前
|
域名解析 运维 监控
阿里云轻量服务器的系统镜像和应用镜像的区别
轻量应用服务器是阿里云推出的易用型云服务器,支持一键部署、域名解析、安全管理和运维监控。本文介绍其系统镜像与应用镜像的区别及选择建议,助您根据业务需求和技术能力快速决策,实现高效部署。

热门文章

最新文章