栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

数据与信息资源共享平台(九)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

数据与信息资源共享平台(九)

滑动验证
  • 官方文档
    • 介绍
    • 友链
  • maven仓库更新依赖(springboot集成)
  • 后端
    • GeetestConfig.java
    • GeetestController.java
    • GeetestLib.java
  • 前端
    • 注册
    • 找回密码
    • 登录

官方文档 介绍

「行为验证」软件主要由以下三个部分组成:
服务端SDK
客户端SDK
智能管理后台

服务端SDK封装了验证服务端所需要配置的接口,完成必要的数据处理。支持c#、java、python、php、node.js、golang、ruby等开发语言。
客户端SDK封装了验证客户端部分, 呈现验证模块的主要交互界面。支持Web、iOS、Android三大平台。
另外,「行为验证」提供智能管理后台,拥有多维度可视化数据帮助你全面把握验证详情;同时还拥有丰富的自定义选项,方便定制你网站的专属验证模块。

友链

文档地址:
https://docs.geetest.com/sensebot/start/
https://docs.geetest.com/gt4/overview/flowchart
服务端:
https://docs.geetest.com/sensebot/deploy/server/java#%E9%85%8D%E7%BD%AE%E5%AF%86%E9%92%A5
Web端:
https://docs.geetest.com/sensebot/deploy/client/web

maven仓库更新依赖(springboot集成)

		org.json
		json
		20171018
	
	
		org.springframework.boot
		spring-boot-starter-data-redis
	
	
		org.projectlombok
		lombok
		1.18.12
	

本项目使用滑块验证

后端 GeetestConfig.java

GeetestWeb配置文件

public class GeetestConfig {

	// 填入自己的captcha_id和private_key
	private static final String geetest_id = ;
	private static final String geetest_key = ;

	public static final String getGeetest_id() {
		return geetest_id;
	}

	public static final String getGeetest_key() {
		return geetest_key;
	}

}
GeetestController.java
@RequestMapping("/geetest")

注册验证

@RequestMapping("/register")
	public Object getValidate(HttpServletRequest request){
		GeetestLib gtSdk = new GeetestLib(GeetestConfig.getGeetest_id(), GeetestConfig.getGeetest_key());
	}

判断是否验证成功

@RequestMapping("/validate")
	public Object validate(HttpServletRequest request){
		GeetestLib gtSdk = new GeetestLib(GeetestConfig.getGeetest_id(), GeetestConfig.getGeetest_key());
		
		String challenge = request.getParameter(GeetestLib.fn_geetest_challenge);
		String validate = request.getParameter(GeetestLib.fn_geetest_validate);
		String seccode = request.getParameter(GeetestLib.fn_geetest_seccode);
		
		//从session中获取gt-server状态
		int gt_server_status_code = (Integer) request.getSession().getAttribute(gtSdk.gtServerStatusSessionKey);
		
		//从session中获取userid
		String userid = (String)request.getSession().getAttribute("userid");
		
		int gtResult = 0;

		if (gt_server_status_code == 1) {
			//gt-server正常,向gt-server进行二次验证
				
			gtResult = gtSdk.enhencedValidateRequest(challenge, validate, seccode, userid);
			System.out.println(gtResult);
		} else {
			// gt-server非正常情况下,进行failback模式验证
			System.out.println("failback:use your own server captcha validate");
			gtResult = gtSdk.failbackValidateRequest(challenge, validate, seccode);
			System.out.println(gtResult);
		}

		if (gtResult == 1) {
			return "success";
		}
		else{
			return "fail";
		}
	}
GeetestLib.java
// 极验验证二次验证表单数据 chllenge

	public static final String fn_geetest_challenge = "geetest_challenge";

// 极验验证二次验证表单数据 validate

	public static final String fn_geetest_validate = "geetest_validate";
	
// 极验验证二次验证表单数据 seccode

	public static final String fn_geetest_seccode = "geetest_seccode";
	

注册结果状态校验

//用captchaID进行注册,更新challenge
//@return 1表示注册成功,0表示注册失败

	private int registerChallenge() {
		try {
			String GET_URL = apiUrl + registerUrl+"?gt=" + this.captchaId;
			if (this.userId != ""){
				GET_URL = GET_URL + "&user_id=" + this.userId;
				this.userId = "";
			}
			gtlog("GET_URL:" + GET_URL);
			String result_str = readContentFromGet(GET_URL);
			gtlog("register_result:" + result_str);
			if (32 == result_str.length()) {

				this.responseStr = this.getSuccessPreProcessRes(this.md5Encode(result_str + this.privateKey));
				
				return 1;
			} else {
				gtlog("gtServer register challenge failed");
				return 0;
			}
		} catch (Exception e) {
			gtlog("exception:register api");
		}
		return 0;
	}

服务器发送请求

	private String readContentFromGet(String getURL) throws IOException {

		URL getUrl = new URL(getURL);
		HttpURLConnection connection = (HttpURLConnection) getUrl
				.openConnection();

		connection.setConnectTimeout(2000);// 设置连接主机超时(单位:毫秒)
		connection.setReadTimeout(2000);// 设置从主机读取数据超时(单位:毫秒)

		// 建立与服务器的连接,并未发送数据
		connection.connect();
		
		// 发送数据到服务器并使用Reader读取返回的数据
		StringBuffer sBuffer = new StringBuffer();

		InputStream inStream = null;
		byte[] buf = new byte[1024];
		inStream = connection.getInputStream();
		for (int n; (n = inStream.read(buf)) != -1;) {
			sBuffer.append(new String(buf, 0, n, "UTF-8"));
		}
		inStream.close();
		connection.disconnect();// 断开连接

		return sBuffer.toString();
	}

服务器二次验证

	public int enhencedValidateRequest(String challenge, String validate, String seccode) {	
		
		if (!resquestIsLegal(challenge, validate, seccode)) {
			return 0;
		}
		gtlog("request legitimate");
		
		String host = baseUrl;
		String path = validateUrl;
		int port = 80;
		String query = String.format("seccode=%s&sdk=%s", seccode,
				(this.sdkLang + "_" + this.verName));
		String response = "";
		
		if (this.userId != ""){
			query = query + "&user_id=" + this.userId;
			this.userId = "";
		}
		gtlog(query);
		try {
			if (validate.length() <= 0) {
				return 0;
			}

			if (!checkResultByPrivate(challenge, validate)) {
				return 0;
			}
			gtlog("checkResultByPrivate");
			response = postValidate(host, path, query, port);

			gtlog("response: " + response);
		} catch (Exception e) {
			e.printStackTrace();
		}

		gtlog("md5: " + md5Encode(seccode));

		if (response.equals(md5Encode(seccode))) {
			return 1;
		} else {
			return 0;
		}
	}
前端 注册

register.html


 else {
                            // 先校验是否点击了验证码
                            var validate = captchaObj.getValidate();
                            if (!validate) {
                                checkForm('请先完成验证', 'popup-captcha');
                                return;
                            }
                            $("#confirmPassword").parent().parent().removeClass('has-error');
                            $("#register").attr('disabled', true);
                            $.ajax({
                                url: known.realpath + '/user/register.do',
                                type: 'post',
                                dataType: 'json',
                                data: $('#registerform').serialize(),
                                success: function (data) {
                                    $("#register").removeAttr("disabled");
                                    // layer.close(loadingindex);
                                    if (data.msg == null) {
                                        var d = dialog({
                                            content: " + known.realpath + "/resources/images/loading.gif' />   注册成功,请尽快登录邮箱激活账户......",
                                        });
                                        d.showModal();
                                        setTimeout(function () {
                                            d.close().remove();
                                            document.location.href = known.realpath;
                                        }, 1500);
                                    } else {
                                        var d = dialog({
                                            width: 200,
                                            content: data.msg,
                                            quickClose: true // 点击空白处快速关闭
                                        });
                                        d.show();
                                    }
                                }
                            });
                        }
// 验证开始需要向网站主后台获取id,challenge,success(是否启用failback)
                $.ajax({
                    url: "${realpath}/geetest/register?t=" + (new Date()).getTime(), // 加随机数防止缓存
                    type: "get",
                    dataType: "json",
                    success: function (data) {
                        // 使用initGeetest接口
                        // 参数1:配置参数
                        // 参数2:回调,回调的第一个参数验证码对象,之后可以使用它做appendTo之类的事件
                        initGeetest({
                            gt: data.gt,
                            challenge: data.challenge,
                            product: "popup", // 产品形式,包括:float,embed,popup。注意只对PC版验证码有效
                            offline: !data.success // 表示用户后台检测极验服务器是否宕机,一般不需要关注
                            // 更多配置参数请参见:http://www.geetest.com/install/sections/idx-client-sdk.html#config
                        }, handlerPopup);
                    }
                });

找回密码

findpassword.html


 

正在加载验证码......

请先拖动验证码到相应位置

  $.ajax({
        // 获取id,challenge,success(是否启用failback)
        url: "${realpath}/geetest/register?t=" + (new Date()).getTime(), // 加随机数防止缓存
        type: "get",
        dataType: "json",
        success: function (data) {
            // 使用initGeetest接口
            // 参数1:配置参数
            // 参数2:回调,回调的第一个参数验证码对象,之后可以使用它做appendTo之类的事件
            initGeetest({
                gt: data.gt,
                challenge: data.challenge,
                product: "embed", // 产品形式,包括:float,embed,popup。注意只对PC版验证码有效
                offline: !data.success // 表示用户后台检测极验服务器是否宕机,一般不需要关注
                // 更多配置参数请参见:http://www.geetest.com/install/sections/idx-client-sdk.html#config
            }, handlerEmbed);
        }
    });

登录

login.html


    // 登录验证
    var handlerPopup = function (captchaObj) {
        $('#login').click(function (event) {
            var account = $('#account').val();
            var password = $('#password').val();
            if (account == null || $.trim(account) == '') {
                checkForm('用户名不能为空', 'account');
                $("#account").parent().addClass('has-error');
            } else if (password == null || $.trim(password) == '') {
                $("#account").parent().removeClass('has-error');
                checkForm('密码不能为空', 'password');
                $("#password").parent().addClass('has-error');
            } else {
                // 先校验是否点击了验证码
                var validate = captchaObj.getValidate();
                if (!validate) {
                    checkForm('请先完成验证', 'popup-captcha');
                    return;
                }
                $("#password").parent().removeClass('has-error');
                var loadingindex = layer.load(0, {
                    shade: [0.1, '#fff'] //0.1透明度的白色背景
                });
                $.ajax({
                    url: known.realpath + '/user/login.do',
                    type: 'POST',
                    dataType: 'json',
                    data: $('#loginform').serialize(),
                    success: function (data) {
                        layer.close(loadingindex);
                        if (data.msg == null) {
                            var d = dialog({
                                content: " + known.realpath + "/resources/images/loading.gif' />   登录成功,跳转中...",
                            });
                            d.showModal();
                            setTimeout(function () {
                                d.close().remove();
                                if (null == known.redirect || known.redirect == "") {
                                    known.redirect = known.realpath;
                                }
                                document.location.href = known.redirect;
                            }, 1000);
                        } else {
                            var d = dialog({
                                width: 200,
                                content: data.msg,
                                quickClose: true // 点击空白处快速关闭
                            });
                            d.show();
                        }
                    }
                });
            }
        });
        // 将验证码加到id为captcha的元素里
        captchaObj.appendTo("#popup-captcha");
    };

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/949067.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号