MVC uses the 7_ verification code to make login verification codes practical tips for learning notes

Source: Internet
Author: User
Tags json md5 rand jquery library

In the previous project, if you need to use a captcha, basically are their own GDI + drawing out, easy to use, but there are some small problems, first of all, if less interference line, the security is not very high, the verification code is easily recognized by the machine, if more than painting too many interference lines, the robot recognition rate of decline, The recognition rate of the human eye also drops synchronously (shocking cry). More importantly, GDI + draw the verification code in general will not be very beautiful, if you do a cool landing interface but with such a verification code, painting wind Strange, ugly to the extreme.

And then the process of browsing the web, found that a lot of web site projects have used a verification code called verification, the use of moving the slider to verify the way, convenient and beautiful. After a search, I learned that the official free edition was enough to deal with most of the projects I had in hand, and I couldn't help but try to use the verification code that I used as a login in the MVC learning process.

The extreme Inspection Official provides C # SDK and demo for developers to refer to, but WebForm version, the readability is not very high, and now use WebForm for Web site development is basically disappeared, I will be the official WebForm code based on the ASP.net MVC program.

Register for a Pole test

To the official website registration account after entering the background management interface, click to add Validation

After adding we can get ID and key

Complete validation Logic

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 Verification of the 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>///Verification API URL///</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>///Verification API Service status session Key///</summary> Public Const String Gtserverstatussessionkey= "Gt_server_status"; <summary>///Validation of the form data Chllenge///</summary> Public const String Fngeetestchallenge = "Geetest" two times
  _challenge "; <summary>///Validation of the form data Validate///</summary> Public const String fngeetestvalidate = "Geetest_" two times
  Validate "; <summary>///Validation of the form data Seccode///</summary> Public const String Fngeetestseccode = "Geetest_se" two times
  Ccode ";
  Private String UserID = "";
  Private String responsestr = "";
  Private String Captchaid = "";

  Private String Privatekey = "";
  <summary>///Validation Success result string///</summary> public const int successresult = 1;
  <summary>///Failure test string///</summary> Public const int failresult = 0;

  <summary>///decision for robot result string///</summary> Public const string forbiddenresult = "forbidden";
  <summary>///Geetestlib Constructor///</summary>///<param name= "PublicKey" > Polarographic Verification Public Key </param> ///<param name= "Privatekey" > Verification private key </param> public geetestlib (String publickey, String privatekey) {THIS.P
   Rivatekey = Privatekey;
  This.captchaid = PublicKey;
   private int Getrandomnum () {Random rand =new Random (); int randres = rand.
   Next (100);
  return randres; ///<summary>///Validation initialization preprocessing///</summary>///<returns> Initialization Results </returns> public Byte PR
   Eprocess () {if (This.captchaid = = null) {Console.WriteLine ("PublicKey is null!");
    else {String challenge = This.registerchallenge (); if (challenge.
     Length = =) {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 = =) {this.getsuccesspreprocessres (challenge);
    return 1;
     else {this.getfailpreprocessres ();
    Console.WriteLine ("Server regist Challenge failed!");

  } return 0;
  Public String Getresponsestr () {return this.responsestr;  ///<summary>///After preprocessing failed return format string///</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 = "{" + string.
  Format ("\ Success\": {0},\ "gt\": \ "{1}\", \ "challenge\": \ "{2}\" ", 0, This.captchaid, challenge) +"} ";
  Standard string///</summary> private void Getsuccesspreprocessres (String challenge) after successful///<summary>///preprocessing {Challenge = This.md5encode (Challenge + This.privatekey); This.responsestr = "{" + string.
  Format ("\ Success\": {0},\ "gt\": \ "{1}\", \ "challenge\": \ "{2}\" ", 1, This.captchaid, Challenge) +"} "; }///<summary>///failback mode validation///</summary>///<param name= "Challenge" >failback mode for use with Val Idate together to decode the answer, to determine whether the validation is correct </param>///<param name= "Validate" >failback mode to decode the answer together with the challenge to determine whether the validation is correct </ param>///<param name= "Seccode" >failback mode, is actually a useless parameter </param>///<returns> validation Results </returns > public int failbackvalidaterequest (String challenge, String validate, String seccode) {if (!this.requestisleg
   Al (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 decodeimggrpindex = this.decoderesponse (challenge, Encodeimggrpindex);
   int validateresult = This.validatefailimage (Decodeans, Decodefullbgimgindex, 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_index + "").
   Substring (10, 10);
   String Answer_decode = ""; for (int i = 0;i < 9; i++) {if (i% 2 = 0) Answer_decode + = Full_bg_name.
    ElementAt (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 <) result = 40;
   if (Math.Abs (Ans-result) < thread) return geetestlib.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>///to gt-server two validation///</summary>///<param name= "challenge" > Unique identification of this authentication session < /param>///<param name= "Validate" The validation result identification string </param>///<param name= "Seccode" by the server side after the finish drag > Verify the result of the checksum code, if Gt-server return is not equal to this value will indicate validation failure </param>///<returns> two times validation results </returns> public int Enhencedvalidaterequest (String challenge, String validate, String seccode) {if (!this.requestislegal, challenge
   Date, Seccode)) return geetestlib.failresult; if (validate. Length > 0 && checkresultbyprivate (Challenge, validate)) {String query = "seccode=" + Seccode + "&s"
    Dk=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; 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 + "&u"
    Ser_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.
   Format ("{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);
   Myrequeststream.write (requestbytes, 0, requestbytes.length);

   Myrequeststream.close (); HttpWebResponse response = (HttpWebResponse) request.
   GetResponse (); Read return info Stream myresponsestream = response.
   GetResponseStream ();
   StreamReader Mystreamreader = new StreamReader (Myresponsestream, encoding.getencoding ("Utf-8"));
   String retstring = Mystreamreader.readtoend ();
   Mystreamreader.close ();

   Myresponsestream.close ();

  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) * + templist.elementat (1);
  return result; private int Decoderesponse (String challenge, String str) {if (str).
   LENGTH&GT;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. Get the Verification code

Introducing the jquery Library

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

Add a div to place the captcha (you need to put it in the form form)

<div id= "Geetest-container" >

</div>
Add JS code to get 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",////using JSONP format
   success:function (data) {/
    /using Initgeetest interface
    // Parameter 1: Configuration parameters that are consistent
    ///Parameter 2: Callback, the first parameter verification code object of the callback, and then use it to do event initgeetest such as Appendto
    ({
     GT: geetest). DATA.GT,
     Challenge:data.challenge,
     product: "float",//Products form
     offline:!data.success
    },
     handler);

 }} var handler = function (captchaobj) {
  //Add the Captcha to the element with ID captcha
  captchaobj.appendto ("#geetest-container");

  captchaobj.onsuccess = function (e) {
   console.log (e);
  }

 };
</script>

The address "/login/geektest" We request asynchronously in the Processgeetest method is to obtain the authentication code is the method that the background needs to execute

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. Verification Code

Note that when the form form is submitted, three and geetest_challenge-related parameters are uploaded to the background method (Geetest_validate, geetest_seccode) and null if the CAPTCHA is not validated successfully.

The background authentication method is:

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 determine in the form whether the verification code has been validated successfully:

Public ActionResult Login ()
{
 if (! Checkgeetestresult ()) return
  Content ("No: Please complete the verification operation first.") ");
 ....
}

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.