captcha实现验证码功能

首先在pom.xml中添加hutool包:

        <dependency>
          <groupId>cn.hutool</groupId>
          <artifactId>hutool-all</artifactId>
          <version>5.2.3</version>
        </dependency>

创建验证码类:CreateCaptcha

public class CreateCaptcha  implements OperationStep{
	private static final Logger logger = LoggerFactory.getLogger(CreateCaptcha.class);
	
	@Override
	public int excute(Operation oper) throws PAIException {
		// TODO Auto-generated method stub
		UUID uuid = UUID.randomUUID();  //生成随机字符串uuid
		//redis中出入的key
		String cacheKey = "captcha:".concat(uuid.toString());
		//获取redis类
		RedisService redisService = oper.getBean("redisService", RedisService.class);
		//随机数
		RandomGenerator randomGenerator = new RandomGenerator("0123456789abcdecghigklmzobqrstuvwsyz", 4);  //生成4个随机数
		//创建验证码
		LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(130,45,4,100);
		lineCaptcha.setGenerator(randomGenerator);
		lineCaptcha.createCode();
		//输出到流
//		try {
//			OutputStream out=oper.getResponse().getOutputStream(); 
//			lineCaptcha.write(out); 
//			
//	        out.flush();
//	        out.close();
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		
		String code=lineCaptcha.getCode();  //获取验证码
		CaptchaObj captchaoObj=new CaptchaObj();
	    captchaoObj.setKey(uuid.toString());
	    captchaoObj.setCode("data:image/png;base64,"+lineCaptcha.getImageBase64().toString());
		redisService.put(cacheKey, code,300);  //添加到redis中,5分钟后失效
		oper.setTranStepSuccResult(captchaoObj);
		
		return 0;
	}

	@Override
	public int init(Map<String, String> param) {
		// TODO Auto-generated method stub
		return 0;
	}

}

验证码校验类:

CheckCaptchaStep

public class CheckCaptchaStep implements OperationStep{
	private static final Logger logger = LoggerFactory.getLogger(CheckCaptchaStep.class);
	
	@Override
	public int excute(Operation oper) throws PAIException {
		DataContext dc = oper.getContext();
		Map<String, Object> input = StepUtils.getInputValue(oper);
		String codekey=Objects.toString(input.get("codekey").toString(), "");  //获取校验码
		String cacheKey = "captcha:".concat(codekey);   //获取校验码key
		RedisService redisService = oper.getBean("redisService", RedisService.class);   //获取redis类
		String cacheCode = Objects.toString(redisService.get(cacheKey), "");  //获取redis中的验证码
		//判断是否有效
		if (cacheCode.isEmpty()) {
			oper.setTranStepFailureResult("验证码已失效.", cacheCode);
			return -1;
		} else {
			String kaptchaCode = Objects.toString(input.get("kaptchaCode").toString(), "");
			if (kaptchaCode.isEmpty()) {
				oper.setTranStepFailureResult("总线参数名定义错误.", cacheCode);
				return -1;
			} else if (!kaptchaCode.equals(cacheCode)) {  //验证码对比
				oper.setTranStepFailureResult("验证码输入不正确.", kaptchaCode);
				return -1;
			} else {
				redisService.remove(cacheKey);
				oper.setTranStepSuccResult("验证码校验正确.");
				return 0;
			}
		}
	}

	@Override
	public int init(Map<String, String> param) {
		// TODO Auto-generated method stub
		return 0;
	}

}

接口配置文件op_captcha.xml代码:

 <operation-cfg>
	<operation id="getcode" name="获取验证码"  type="api" token="false">
		<step id="getcode" on0Target="return" onOtherTarget="error" class="step.CreateCaptcha">

		</step>
	</operation>
	
	<operation id="kaptcha/check" name="验证码校验"  type="api" token="false">
		<context>
			<Record name="input">
			    <string name="codekey" required="true" desc="唯一值"/>
				<string name="kaptchaCode" required="true" desc="验证码"/>
			</Record>
		</context>
		<step id="insertStep" on0Target="return" onOtherTarget="error" class="step.CheckCaptchaStep">
			<context>
				<string name="mapSet">input</string>
			</context>
		</step>		
	</operation>
	
</operation-cfg>

生成样式

 ajax调用 

	function getCode(){
		$.ajax({
			type: "post",
			dataType:"json",
			url:"http://{}/wtdf/json/getcode",
			success:function(data){
				//console.log(data);
				if(data.errCode==0){
					var codekey=data.data.key;
					$("#vercode").attr("src",data.data.code);  //二进制直接赋给src
				}else{
					layer.msg("验证码获取错误");
				}
			}
		  });
	}

样式 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
您可以使用Python中的验证码来增加网站的安全性,防止垃圾邮件机器人的滥用和DDOS攻击。其中一个常用的Python库是django-simple-captcha,您可以使用pip命令进行安装(pip install django-simple-captcha)。然后,在您的代码中导入captcha.py模块(import captcha.py)并使用它来生成验证码(captcha.CAPTCHA()) [1。 在您的表单类中,您可以将验证码字段添加为CaptchaField,这样用户就需要输入正确的验证码才能提交表单。例如,在Django中,您可以这样设置captcha字段: from django import forms from captcha.fields import CaptchaField class UserRegisterForm(forms.Form): email = forms.EmailField(required=True) password = forms.CharField(required=True, min_length=3, max_length=15, error_messages={ 'required': '密码必须填写', 'min_length': '密码不得小于3位', 'max_length': '密码不得大于15位' }) captcha = CaptchaField(error_messages={ 'invalid': '验证码错误' }) [3] 这样,用户在填写表单时需要输入正确的验证码才能通过验证。这有助于防止自动化程序对您的网站进行恶意操作。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [python-captcha:python中的验证码](https://download.csdn.net/download/weixin_42131728/16144121)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] - *2* *3* [python通过captcha实现验证码功能](https://blog.csdn.net/weixin_40970987/article/details/92783459)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值