MVC creates logon verification code learning notes using polar verification 7. mvc learning notes

Source: Internet
Author: User

MVC creates logon verification code learning notes using polar verification 7. mvc learning notes

In previous projects, if verification codes were needed, they were drawn by using GDI +, which is simple and easy to use, but there are also some small problems. First, if there are few interference lines, the security is not very high, and the verification code is easy to be recognized by machines. If too many lines are painted to interfere with the robot's recognition rate, the recognition rate of the human eye will also decrease (stunned ). More importantly, the verification code drawn by GDI + is generally not very beautiful. If a cool login interface is configured with such a verification code, the style is strange and ugly.

Later, when browsing the Web page, we found that many website projects use a verification code called "Excellent Verification", which is verified by moving the slider to make it more convenient and beautiful. After some searches, I learned that the official free version is enough to cope with most of my projects. I can't help but try to use extreme verification as the login verification code during the MVC learning process.

The official website provides C # sdks and demos for developers to refer to. However, they are only in the Webform version and are not very readable. Currently, Webform is used for website development, based on the official Webform code, I will use it in ASP.. net mvc program.

Registration polar Verification

After registering an account on the Zhuji official website, go to the background management page and click Add verification.

We can get the ID and KEY after adding them.

Verification logic completed

1. First, we need to introduce the official Geetestlib class.

Using System; using System. collections; using System. collections. generic; using System. linq; using System. text; using System. security. cryptography; using System. net; using System. IO; namespace PMS. webApp. models {// <summary> /// GeetestLib excellent verification C # SDK basic library /// </summary> public class GeetestLib {// <summary> /// SDK version number // </summary> public const String version = "3.2.0 "; /// <summary> /// SDK development language /// </summary> public const String sdkLang = "csharp "; /// <summary> /// api url for polar verification /// </summary> protected const String apiUrl =" http://api.geetest.com "; /// <Summary> /// register url /// </summary> protected const String registerUrl ="/register. php "; // <summary> // validate url // </summary> protected const String validateUrl ="/validate. php "; /// <summary> /// the Session Key in the API service status for polar verification /// </summary> public const String gtServerStatusSessionKey =" gt_server_status "; /// <summary> /// secondary verification form data Chllenge /// </summary> public const String FnGeetestChallenge = "geetest_challenge"; // <summary> // Validate the second verification form data Validate /// </summary> public const String fnGeetestValidate = "geetest_validate "; /// <summary> /// second verification form data Seccode for polar verification /// </summary> public const String fnGeetestSeccode = "geetest_seccode"; private String userID = ""; private String responseStr = ""; private String captchaID = ""; private String privateKey = ""; // <su Mmary> /// string of the successful verification result /// </summary> public const int successResult = 1; /// <summary> /// verification result string // </summary> public const int failResult = 0; /// <summary> /// indicates the result String of the robot. /// </summary> public const String forbiddenResult = "forbidden "; /// <summary> /// GeetestLib constructor /// </summary> /// <param name = "publicKey"> polar verification Public Key </param> // /<param name = "privateKey"> polar verification Private Key </param> public GeetestLib (Str Ing publicKey, String privateKey) {this. privateKey = privateKey; this. captchaID = publicKey;} private int getRandomNum () {Random rand = new Random (); int randRes = rand. next (100); return randRes ;} /// <summary> /// verify initialization preprocessing /// </summary> /// <returns> initialization result </returns> public Byte preProcess () {if (this. captchaID = null) {Console. writeLine ("publicKey is null! ");} Else {String challenge = this. registerChallenge (); if (challenge. length = 32) {this. getSuccessPreProcessRes (challenge); return 1;} else {this. getFailPreProcessRes (); Console. writeLine ("Server regist challenge failed! ") ;}} Return 0;} public Byte preProcess (String userID) {if (this. captchaID = null) {Console. WriteLine (" publicKey is null! ");} Else {this. userID = userID; String challenge = this. registerChallenge (); if (challenge. length = 32) {this. getSuccessPreProcessRes (challenge); return 1;} else {this. getFailPreProcessRes (); Console. writeLine ("Server regist challenge failed! ") ;}} Return 0;} public String getResponseStr () {return this. responseStr;} /// <summary> // format string returned after preprocessing fails /// </summary> private void getFailPreProcessRes () {int rand1 = this. getRandomNum (); int rand2 = this. getRandomNum (); String md5Str1 = this. md5Encode (rand1 + ""); String md5Str2 = this. md5Encode (rand2 + ""); String challenge = md5Str1 + md5Str2. substring (0, 2); this. responseStr = "{" + st Ring. format ("\" success \ ": {0}, \" gt \ ": \" {1} \ ", \" challenge \": \ "{2} \" ", 0, this. captchaID, challenge) + "}" ;}/// <summary> // standard String after successful preprocessing /// </summary> private void getSuccessPreProcessRes (String challenge) {challenge = this. md5Encode (challenge + this. privateKey); this. responseStr = "{" + string. format ("\" success \ ": {0}, \" gt \ ": \" {1} \ ", \" challenge \": \ "{2} \" ", 1, this. captchaID, challenge) + "}";} /// <Summary> /// failback mode verification method /// </summary> /// Decoding with validate in failback Mode answer, determine whether the verification is correct </param> // <param name = "validate"> In failback mode, decode the answer with challenge, verify whether the verification is correct </param> // <param name = "seccode"> In failback mode, it is actually a useless parameter </param> /// <returns> Verification Result </returns> public int failbackValidateRequest (String challenge, String validate, String seccode) {if (! This. requestIsLegal (challenge, validate, seccode) return GeetestLib. failResult; String [] validateStr = validate. split ('_'); String encodeAns = validateStr [0]; String encodeFullBgImgIndex = validateStr [1]; String encodeImgGrpIndex = validateStr [2]; int decodeAns = this. decodeResponse (challenge, encodeAns); int decodeFullBgImgIndex = this. decodeResponse (challenge, encodeFullBgImgIndex); int decodeIm GGrpIndex = this. decodeResponse (challenge, encodeImgGrpIndex); int validateResult = this. validateFailImage (decodeAns, expire, decodeImgGrpIndex); return validateResult;} private int validateFailImage (int ans, int full_bg_index, int img_grp_index) {const int thread = 3; String full_bg_name = this. md5Encode (full_bg_index + ""). substring (0, 10); String bg_name = md5Encode (img_grp_inde X + ""). substring (10, 10); String answer_decode = ""; for (int I = 0; I <9; I ++) {if (I % 2 = 0) answer_decode + = Convert (I); else if (I % 2 = 1) answer_decode + = bg_name.ElementAt (I);} String x_decode = answer_decode.Substring (4); int x_int = Convert. toInt32 (x_decode, 16); int result = x_int % 200; if (result <40) result = 40; if (Math. abs (ans-result) <thread) return Geetes TLib. successResult; else return GeetestLib. failResult;} private Boolean requestIsLegal (String challenge, String validate, String seccode) {if (challenge. equals (string. empty) | validate. equals (string. empty) | seccode. equals (string. empty) return false; return true ;} /// <summary> /// perform secondary verification on the gt-server /// </summary> /// <param name = "challenge"> unique identifier of the verification session </param> /// <param name = "validate"> drag to finish The verification result string returned by the server </param> // <param name = "seccode"> the verification code of the verification result, if the value returned by gt-server is not equal to this value, the verification fails </param> /// <returns> secondary verification result </returns> public int enhencedValidateRequest (String challenge, string validate, String seccode) {if (! This. requestIsLegal (challenge, validate, seccode) return GeetestLib. failResult; if (validate. length> 0 & checkResultByPrivate (challenge, validate) {String query = "seccode =" + seccode + "& sdk = csharp _" + GeetestLib. version; String response = ""; try {response = postValidate (query);} catch (Exception e) {Console. writeLine (e);} if (response. equals (md5Encode (seccode) {return GeetestLib. succ EssResult ;}} return GeetestLib. failResult;} public int enhencedValidateRequest (String challenge, String validate, String seccode, String userID) {if (! This. requestIsLegal (challenge, validate, seccode) return GeetestLib. failResult; if (validate. length> 0 & checkResultByPrivate (challenge, validate )) {String query = "seccode =" + seccode + "& user_id =" + userID + "& sdk = csharp _" + GeetestLib. version; String response = ""; try {response = postValidate (query);} catch (Exception e) {Console. writeLine (e);} if (response. equals (md5Encode (seccode ))){ Return GeetestLib. successResult;} return GeetestLib. failResult;} private String readContentFromGet (String url) {try {HttpWebRequest request = (HttpWebRequest) WebRequest. create (url); request. timeout = 20000; HttpWebResponse response = (HttpWebResponse) request. getResponse (); Stream myResponseStream = response. getResponseStream (); StreamReader myStreamReader = new StreamReader (myResponseStream, Encoding. getEncoding ("UTF-8"); String retString = myStreamReader. readToEnd (); myStreamReader. close (); myResponseStream. close (); return retString;} catch {return "" ;}} private String registerChallenge () {String url = ""; if (string. empty. equals (this. userID) {url = string. format ("{0} {1 }? Gt = {2} ", GeetestLib. apiUrl, GeetestLib. registerUrl, this. captchaID);} else {url = string. Format (" {0} {1 }? Gt = {2} & user_id = {3} ", GeetestLib. apiUrl, GeetestLib. registerUrl, this. captchaID, this. userID);} string retString = this. readContentFromGet (url); return retString;} private Boolean checkResultByPrivate (String origin, String validate) {String encodeStr = md5Encode (privateKey + "geetest" + origin); return validate. equals (encodeStr);} private String postValidate (String data) {String url = string. fo Rmat ("{0} {1}", GeetestLib. apiUrl, GeetestLib. validateUrl); HttpWebRequest request = (HttpWebRequest) WebRequest. create (url); request. method = "POST"; request. contentType = "application/x-www-form-urlencoded"; request. contentLength = Encoding. UTF8.GetByteCount (data); // send data Stream myRequestStream = request. getRequestStream (); byte [] requestBytes = System. text. encoding. ASCII. getBytes (data); myReques TStream. write (requestBytes, 0, requestBytes. length); myRequestStream. close (); HttpWebResponse response = (HttpWebResponse) request. getResponse (); // read the returned information Stream myResponseStream = response. getResponseStream (); StreamReader myStreamReader = new StreamReader (myResponseStream, Encoding. getEncoding ("UTF-8"); string retString = myStreamReader. readToEnd (); myStreamReader. close (); myResponseStream. clos E (); return retString;} private int decodeRandBase (String challenge) {String baseStr = challenge. substring (32, 2); List <int> tempList = new List <int> (); for (int I = 0; I <baseStr. length; I ++) {int tempAscii = (int) baseStr [I]; tempList. add (tempAscii> 57 )? (TempAscii-87): (tempAscii-48);} int result = tempList. elementAt (0) * 36 + tempList. elementAt (1); return result;} private int decodeResponse (String challenge, String str) {if (str. length> 100) return 0; int [] shuzi = new int [] {1, 2, 5, 10, 50}; String chongfu = ""; hashtable key = new Hashtable (); int count = 0; for (int I = 0; I <challenge. length; I ++) {String item = challenge. elementAt (I) + ""; if (chongfu. contains (item) continue; else {int value = shuzi [count % 5]; chongfu + = item; count ++; key. add (item, value) ;}} int res = 0; for (int I = 0; I <str. length; I ++) res + = (int) key [str [I] + ""]; res = res-this. decodeRandBase (challenge); return res;} private String md5Encode (String plainText) {MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider (); string t2 = BitConverter. toString (md5.ComputeHash (UTF8Encoding. default. getBytes (plainText); t2 = t2.Replace ("-", ""); t2 = t2.ToLower (); return t2 ;}}}

2. Obtain the verification code

Introduce Jquery Library

<Script src = "~ /Content/plugins/jquery/jquery-1.8.2.min.js "> </script>

Add the div used to place the verification code (to be placed in the form)

<Div id = "geetest-container">

</Div>
Add JS Code to obtain the verification code

<Script> window. addEventListener ('load', processGeeTest); function processGeeTest () {$. ajax ({// get id, challenge, success (whether failback is enabled) url: "/Login/GeekTest", type: "get", dataType: "json ", // use the jsonp format success: function (data) {// use the initGeetest interface // parameter 1: configuration parameter, consistent with the parameter accepted when the Geetest instance is created // parameter 2: callback: the first parameter verification code object in the callback. You can use it to perform events such as initGeetest ({gt: data. gt, challenge: data. challenge, product: "float ",/ /Product form offline :! Data. success}, handler) ;}});} var handler = function (captchaObj) {// Add the verification code to the captchaObj element whose id is captcha. appendTo ("# geetest-container"); captchaObj. onSuccess = function (e) {console. log (e) ;}}; </script>

In the processGeeTest method, the address "/Login/GeekTest" of our asynchronous request is the method that needs to be executed in the background to obtain the verification code.

public ActionResult GeekTest(){ return Content(GetCaptcha(),"application/json");}private string GetCaptcha(){ var geetest = new GeetestLib("3594e0d834df77cedc7351a02b5b06a4", "b961c8081ce88af7e32a3f45d00dff84"); var gtServerStatus = geetest.preProcess(); Session[GeetestLib.gtServerStatusSessionKey] = gtServerStatus; return geetest.getResponseStr();}

3. Verify the verification code

Note: When a form is submitted, three parameters related to the polar verification will be uploaded to the background method (geetest_challenge, geetest_validate, geetest_seccode). If the verification code is not verified successfully, the parameter is null.

The background verification method is as follows:

private bool CheckGeeTestResult(){ var geetest = new GeetestLib("3594e0d834df77cedc7351a02b5b06a4", "b961c8081ce88af7e32a3f45d00dff84 "); var gtServerStatusCode = (byte)Session[GeetestLib.gtServerStatusSessionKey]; var userId = (string)Session["userID"]; var challenge = Request.Form.Get(GeetestLib.fnGeetestChallenge); var validate = Request.Form.Get(GeetestLib.fnGeetestValidate); var seccode = Request.Form.Get(GeetestLib.fnGeetestSeccode); var result = gtServerStatusCode == 1 ? geetest.enhencedValidateRequest(challenge, validate, seccode, userId) : geetest.failbackValidateRequest(challenge, validate, seccode); return result == 1;}

We can check whether the verification code is successfully verified in the form:

Public ActionResult Login () {if (! CheckGeeTestResult () return Content ("no: complete the verification first. ");....}

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.