前言
最近在網上偶然看見一個驗證碼,覺得很有意思,於是搜了下,是使用第三方實現的,先看效果:
總體來說效果還是可以的,官方提供的SDK也比較詳細,可配置性很高。在這里在簡單啰嗦幾句使用方式:
使用步驟
①進入官網下載sdk接口→ http://www.geetest.com/install/ ,因為小弟是做C#的,所以此處選擇C#,具體選擇看各位大佬所用語言決定~
②第二步,獲取代碼,訪問紅框所示地址,下載demo。
③運行Demo(src文件夾里面的GeetestSDK項目)
④移植到自己項目中
⑴先將上述src文件拷貝到本地項目根目錄下面
⑵然后打開本地項目並添加現有項目,將GeetestSDK添加進來
⑶在本地項目中添加引用
⑷View中新建容器存放驗證碼
@using (Html.BeginForm()) { <div> 用戶名: </div> <div> @Html.TextBoxFor(model => model.Name) </div> <div> 密碼: </div> <div> @Html.PasswordFor(model => model.Age) </div> <div> 驗證碼:<div id="captcha"></div> @*新增的存放驗證碼的容器*@ </div> <div> <input type="submit" value="登陸" /> </div> }
界面入下圖:
⑸新建一個控制器(GetcaptchaController)和分部視圖(Index)用於顯示請求到的頁面
控制器代碼
public ActionResult Index() { Response.ContentType = "application/json"; Response.Write(getCaptcha()); Response.End(); return View(); } private String getCaptcha() { GeetestLib geetest = new GeetestLib(GeetestConfig.publicKey, GeetestConfig.privateKey); String userID = "ShowTime"; Byte gtServerStatus = geetest.preProcess(userID); Session[GeetestLib.gtServerStatusSessionKey] = gtServerStatus; Session["userID"] = userID; return geetest.getResponseStr(); }
其中,GeetestConfig是新建的一個類,里面代碼如下:
public const String publicKey = "b46d1900d0a894591916ea94ea91bd2c"; public const String privateKey = "36fc3fe98530eea08dfc6ce76e3d24c4";
注:需要引入此命名空間 using GeetestSDK;
Index視圖里面放一個空div就行,代碼如下:
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> </head> <body> <form id="form1"> <div> </div> </form> </body> </html>
⑹使用Ajax在登錄頁加載分部視圖Index用於顯示驗證碼
var handler = function (captchaObj) { //將驗證碼加到id為captcha的元素里 captchaObj.appendTo("#captcha"); }; //極驗 $.ajax({ // 獲取id,challenge,success(是否啟用failback) url: "/Getcaptcha/Index", type: "get", dataType: "json", // 使用jsonp格式 success: function (data) { // 使用initGeetest接口 // 參數1:配置參數,與創建Geetest實例時接受的參數一致 // 參數2:回調,回調的第一個參數驗證碼對象,之后可以使用它做appendTo之類的事件 initGeetest({ gt: data.gt, challenge: data.challenge, product: "float", // 產品形式 offline: !data.success }, handler); } });
注:需在頭部引入Jquery1.9可直接引入下面兩個js
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script> <script src="http://static.geetest.com/static/tools/gt.js"></script>
⑺在登陸按鈕中判斷驗證是否通過,登陸的Index代碼如下:
[HttpPost] public ActionResult Index(Models.HelloModel loginModel) { GeetestLib geetest = new GeetestLib(GeetestConfig.publicKey, GeetestConfig.privateKey); Byte gt_server_status_code = (Byte)Session[GeetestLib.gtServerStatusSessionKey]; String userID = (String)Session["userID"]; int result = 0; String challenge = Request.Form.Get(GeetestLib.fnGeetestChallenge); String validate = Request.Form.Get(GeetestLib.fnGeetestValidate); String seccode = Request.Form.Get(GeetestLib.fnGeetestSeccode); if (gt_server_status_code == 1) result = geetest.enhencedValidateRequest(challenge, validate, seccode, userID); else result = geetest.failbackValidateRequest(challenge, validate, seccode); if (result == 1) Response.Write("success");//返回1則表明驗證通過,可跳轉頁面或者做其他處理 else Response.Write("fail"); return View(); }
運行效果
另:官方Demo下載下來是使用的嵌入式的驗證效果,要更改此效果,可參考客戶端SDK參數來配置
鏈接→ http://www.geetest.com/install/sections/idx-client-sdk.html#id19
Demo下載
鏈接: 點我下載 密碼:63pd
常規驗證碼
最終效果
HTML
<div style="MARGIN-TOP: 12px; margin-left: 0px; width: 130px; float: left;" id="checkInputLine" class="loginFormIpt showPlaceholder"> <input id="checkInput" class="loginFormCheckCodeInput" title='Please enter the contents of the right picture' tabindex="4" maxlength="5" require="True" title='驗證碼' placeholder="驗證碼" type="text" name="vcode" /> </div> <!-- 請輸入驗證碼--> <img id="checkloing" src="/Home/VCode" class="loginFormCheckCodeImg" onclick="reloadcode('/Home/VCode')" title="Can not see clearly, change one." />
Ajax 請求如下:
//刷新驗證碼 function reloadcode(srcStr) { document.getElementById("checkloing").src = srcStr + "?rand=" + Math.random(); } var checkInfo = ""; //檢查數據 function Check() { checkInfo = ""; //檢查不能為空的數據 $("input[Require='True']").each(function (i) { var tmpName = $(this).attr("name"); var strVal = $(this).val(); strVal = strVal.replace(/\s/g, "") if (!strVal) checkInfo += $(this).attr("placeholder") + "不能為空。<br/>"; }); if (checkInfo) return false; return true; } $(function () { $("#btnLogin").click(function () { var ii = layer.load(); if (!Check()) { layer.close(ii); layer.msg('' + checkInfo, function () { }); return; } $("#loadingDiv").show(); $.ajax({ url: "/Home/Index", type: "post", data: "userName=" + $("#tbUserName").val() + "&pwd=" + $("#tbPWD").val() + "&code=" + $("#checkInput").val(), success: function (data) { debugger; if (data.Result == "0") { layer.close(ii); layer.msg('' + data.MSG); return; } else if (data.Result == "1") { layer.close(ii); window.location.href = "/Home/Index"; } }, error: function (data) { layer.close(ii); layer.msg('' + data.MSG); } }); }); });
其中:
layer.msg('' + data.MSG); 這種彈框方式使用了layer彈出層
Home控制器里面的VCde方法就是獲取到最新的驗證碼,代碼如下:
[AllowAnonymous]//跳過登陸驗證 public ActionResult VCode() { VerificationCodeHelper vcode = new VerificationCodeHelper(); string codeStr = vcode.GetRandomCode(); if (!string.IsNullOrEmpty(codeStr)) { byte[] arrImg = vcode.GetVCode(codeStr); Session["code"] = codeStr; return File(arrImg, "image/gif"); } else { return RedirectToAction("/Login/VCode?rand=" + Guid.NewGuid().ToString().Substring(1, 10), "image/jpeg"); } }
其中 VerificationCodeHelper 就是封裝好的 生成驗證碼的類,直接使用就行,代碼如下:

public class VerificationCodeHelper { private static Color BackColor = Color.White; private static int Width = 62; private static int Height = 21; private Random _random; // private string _code; private int _brushNameIndex; public byte[] GetVCode(string codeStr) { _random = new Random(); using (Bitmap img = new Bitmap(Width, Height)) { // _code = GetRandomCode(); // System.Web.HttpContext.Current.Session["vcode"] = _code; using (Graphics g = Graphics.FromImage(img)) { g.Clear(Color.White);//繪畫背景顏色 Paint_Text(g, codeStr);// 繪畫文字 // g.DrawString(strCode, new Font("微軟雅黑", 15), Brushes.Blue, new PointF(5, 2));// 繪畫文字 Paint_TextStain(img);// 繪畫噪音點 g.DrawRectangle(Pens.DarkGray, 0, 0, Width - 1, Height - 1);//繪畫邊框 using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { //將圖片 保存到內存流中 img.Save(ms, System.Drawing.Imaging.ImageFormat.Gif); //將內存流 里的 數據 轉成 byte 數組 返回 return ms.ToArray(); } } } } /// <summary> /// 繪畫文字 /// </summary> /// <param name="g"></param> private void Paint_Text(Graphics g, string code) { g.DrawString(code, GetFont(), GetBrush(), 3, 1); } /// <summary> /// 繪畫文字噪音點 /// </summary> /// <param name="g"></param> private void Paint_TextStain(Bitmap b) { string[] BrushName = new string[] { "OliveDrab", "ForestGreen", "DarkCyan", "LightSlateGray", "RoyalBlue", "SlateBlue", "DarkViolet", "MediumVioletRed", "IndianRed", "Firebrick", "Chocolate", "Peru", " enrod" }; for (int n = 0; n < 30; n++) { int x = _random.Next(Width); int y = _random.Next(Height); b.SetPixel(x, y, Color.FromName(BrushName[_brushNameIndex])); } } /// <summary> /// 隨機取一個字體 /// </summary> /// <returns></returns> private Font GetFont() { string[] FontItems = new string[]{ "Arial", "Helvetica", "Geneva", "sans-serif", "Verdana" }; int fontIndex = _random.Next(0, FontItems.Length); FontStyle fontStyle = GetFontStyle(_random.Next(0, 2)); return new Font(FontItems[fontIndex], 12, fontStyle); } /**/ /**/ /**/ /// <summary> /// 隨機取一個筆刷 /// </summary> /// <returns></returns> private Brush GetBrush() { Brush[] BrushItems = new Brush[]{ Brushes.OliveDrab, Brushes.ForestGreen, Brushes.DarkCyan, Brushes.LightSlateGray, Brushes.RoyalBlue, Brushes.SlateBlue, Brushes.DarkViolet, Brushes.MediumVioletRed, Brushes.IndianRed, Brushes.Firebrick, Brushes.Chocolate, Brushes.Peru, Brushes.Goldenrod }; int brushIndex = _random.Next(0, BrushItems.Length); _brushNameIndex = brushIndex; return BrushItems[brushIndex]; } /// <summary> /// 繪畫背景顏色 /// </summary> /// <param name="g"></param> private void Paint_Background(Graphics g) { g.Clear(BackColor); } /**/ /**/ /**/ /// <summary> /// 取一個字體的樣式 /// </summary> /// <param name="index"></param> /// <returns></returns> private FontStyle GetFontStyle(int index) { switch (index) { case 0: return FontStyle.Bold; case 1: return FontStyle.Italic; default: return FontStyle.Regular; } } /// <summary> /// 取得一個 4 位的隨機碼 /// </summary> /// <returns></returns> public string GetRandomCode() { return Guid.NewGuid().ToString().Substring(0, 5); } }
注意,初次加載頁面的時候,將拿到的code存入Session中,點擊登錄的時候,將用戶輸入的驗證碼傳入后台,進行比對驗證是否和Session中的驗證碼相同,如果相同,則允許登錄,否則,驗證碼錯誤
參考Action如下:
[HttpPost] public ActionResult Index(string userName, string pwd) { try { string vccode = Request.Form["code"]; if (string.IsNullOrEmpty(vccode)) return Json(new { Result = "0", MSG = "請填寫驗證碼" }); else { if (Session["code"] == null) return Json(new { Result = "0", MSG = "驗證碼已過期,請點擊刷新驗證碼" }); string str = Session["code"].ToString(); str = str.ToLower(); vccode = vccode.ToLower(); if (str != vccode) return Json(new { Result = "0", MSG = "驗證碼填寫錯誤!" }); else { Session["code"] = null; } if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(pwd)) { return Json(new { Result = "0", MSG = "用戶或密碼沒有填寫" }); } //查詢此用戶 #region 查詢此用戶 List<Models.MySqlUser> adminml = new List<Models.MySqlUser>(); Models.MySqlUser admin = new Models.MySqlUser(); adminml = IBCodeBll.GetModelList(userName.Trim()); if (adminml.Count > 0) { if (!adminml[0].password.ToLower().Equals(Maticsoft.Common.DEncrypt.DESEncrypt.Encrypt2(pwd.Trim()).ToLower())) { return Json(new { Result = "0", MSG = "密碼錯誤!" }); } } else { return Json(new { Result = "0", MSG = "用戶不在在!" }); } #endregion Session["UserName"] = userName.Trim().ToString(); return Json(new { Result = "1", MSG = "登錄成功!" }); } } catch (Exception ex) { return Json(new { Result = "0", MSG = ex.Message }); } }
End!