在介绍之前,首先一个概念明确一个共识:没有攻不破的网站,只有值不值得。
这意思是说,我们可以尽可能的提高自己网站的安全,但并没有绝对的安全,当网站安全级别大于攻击者能得到的回报时,你的网站就是安全的。
所以百度搜到的很多验证码都已经结合了人工智能分析用户行为,很厉害。但这里只介绍我的小网站是怎么设计的。
大概逻辑:当需要验证码时,前端发送ajax向后台请求相关数据发送回前端,由前端生成(与后端生成图片,然后传送图片到前端的做法相比安全性要差很多。但也是可以预防的,后端可以对此Session进行请求记录,如果在一定时间内恶意多次请求,可以进行封禁ip等对策),验证完成后,后台再对传回的数据进行校验。
效果图:


1|0js类的设计:
1.定义一个验证码父类,因为目前只有这一个验证类型,倘若以后再要扩展其他验证类型呢。那么它们之间肯定有很多公共之处(如:验证成功、失败的回调,获取验证码的类型,获取验证结果等),所以这些共同点可以提炼出来,下面是我目前的父类样子:
/**
* 验证码的父类,所有验证码都要继承这个类
* @param id 验证码的唯一标识
* @param type 验证码的类型
* @param contentDiv 包含着验证码的DIV
* @constructor
*/
var Identifying = function (id,type,contentDiv){
this.id = id;
this.type = type;
this.contentDiv=contentDiv;
}
/**
* 销毁函数
*/
Identifying.prototype.destroy = function(){
this.successFunc = null;
this.errorFunc = null;
this.clearDom();
this.contentDiv = null;
}
/**
* 清除节点内容
*/
Identifying.prototype.clearDom = function(){
if(this.contentDiv instanceof jQuery){
this.contentDiv.empty();
}else if(this.contentDiv instanceof HTMLElement){
this.contentDiv.innerText = "";
}
}
/**
* 回调函数
* 验证成功后进行调用
* this需要指具体验证类
* @param result 对象,有对应验证类的传递的参数,具体要看验证类
*/
Identifying.prototype.success = function (result) {
if(this.successFunc instanceof Function){
this.successFunc(result);
}
}
/**
* 验证失败发生错误调用的函数
* @param result
*/
Identifying.prototype.error = function (result) {
if(this.errorFunc instanceof Function){
this.errorFunc(result);
}else{
//统一处理错误
}
}
/**
* 获取验证码id
*/
Identifying.prototype.getId = function () {
return this.id;
}
/**
* 获取验证码类型
* @returns {*}
*/
Identifying.prototype.getType = function () {
return this.type;
}
/**
* 显示验证框
*/
Identifying.prototype.showIdentifying = function(callback){
this.contentDiv.show(null,callback);
}
/**
* 隐藏验证框
*/
Identifying.prototype.hiddenIdentifying = function(callback){
this.contentDiv.hide(null,callback);
}
/**
* 获得验证码显示的dom元素
*/
Identifying.prototype.getContentDiv = function () {
return this.contentDiv;
}
内容版权声明:除非注明,否则皆为本站原创文章。
