Mã nguồn ví dụ xác thực BotDetect ASP CAPTCHA dùng Ajax

Mã nguồn ví dụ BotDetect ASP CAPTCHA này mô tả cách sử dụng Ajax asynchronous requests để tăng tính năng sử dụng cho CAPTCHA.

Nó sử dụng thư viện jQuery để tạo asynchronous requests và phân tích kết quả JSON được trả về bởi việc xác thực bằng mã nguồn ASP. Khi người sử dụng nhập sai câu trả lời, thông báo lỗi hiện ra nhanh hơn. Vì lý do bảo mật, việc xác thực được thực hiện cả hai phía máy khách và máy chủ.

Vị trí lưu dự án mẫu

Mặc định, ví dụ mẫu này được cài đặt tại thư mục
c:\Program Files\Lanapsoft\BotDetect\ASP\v2.0\Samples\CaptchaAjaxValidation\.

Bạn có thể chạy từ Start Menu:
Programs > Lanapsoft > BotDetect > ASP > v2.0 > Samples > CAPTCHA Ajax Validation Sample.

BotDetectAjaxDemo.asp

Mã nguồn đầy đủ

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
  <head>
    <title>BotDetect CAPTCHA ASP Ajax Demo - Input Page</title>
    <link type='text/css' rel='Stylesheet' href="FormStyle.css" />
    <script type="text/javascript" src="BotDetectScript.js"></script>
    <script type="text/javascript" src="BotDetectAjaxValidation.js">
    </script>
    <script type="text/javascript" src="jquery-1.2.3.pack.js">
    </script>
  </head>
  <body>
    <form name="SampleForm" id="SampleForm" method="post" 
      action="ProcessFormAjax.asp">
    <fieldset id="SampleFields">
      <legend>Sample input form</legend>
      <div class="input">
        <label for="FirstName">First Name:</label>
        <input name="FirstName" id="FirstName" type="text" 
          class="textbox" value="<%=Request("FirstName") %>" />
      </div>
      <div class="input">
        <label for="LastName">Last Name:</label>
        <input name="LastName" type="text"  id="LastName" 
        class="textbox" value="<%= Request("LastName") %>" />
      </div>
    </fieldset>
    <fieldset id="CaptchaValidation">
      <legend>CAPTCHA Validation</legend>
      <div id="PromptDiv">Retype the code from the picture</div>
      <div id="CaptchaDiv">
        <div id="CaptchaImage">
          <img id="SampleForm_CaptchaImage" src="
            LanapBotDetectHandler.asp?Command=CreateImage&
            TextStyle=4&ImageWidth=238&ImageHeight=50&
            CodeLength=5&CodeType=0" alt='CAPTCHA Code Image' />
        </div>
        <div id="CaptchaIcons">
          <a href="LanapBotDetectHandler.asp?Command=CreateSound" 
            onclick='LBD_LoadSound("SampleForm_SoundPlaceholder", 
            "LanapBotDetectHandler.asp?Command=CreateSound");
            return false;' title="Speak the code"><img src="
            speaker.gif" alt="Speak the code" /></a>
          <a href="#" onclick='LBD_ReloadImage(
            "SampleForm_CaptchaImage"); return false;' 
            title="Change the code"><img src="reload.gif" 
            alt="Thay đổi mã" /></a>
          <div id='SampleForm_SoundPlaceholder' class="placeholder">
            &nbsp;</div>
        </div>
      </div>
      <div class="input">
        <label for="CaptchaCode">Code:</label>
        <input name="CaptchaCode" id="CaptchaCode" type="text" 
          class="textbox" onkeyup="this.value = 
          this.value.toLowerCase();" />
      </div>
      <%
        If Request("WrongCode") <> "" then
          Response.Write("<div><span id='CodeIncorrectLabel'>
            Incorrect code!</span></div>")
        Else
          Response.Write("<div><span id='CodeIncorrectLabel' 
            style='visibility:hidden;'>Incorrect code!</span></div>")
        End if 	
      %>
      </fieldset>
      <div id="ActionDiv">
        <input type="submit" name="ProcessForm" value="Process Form" 
          id="ProcessForm" onclick="return LBD_Validate();" />
      </div>
      <div id="Note">
        <span>NOTE: the Trial version will use "LANAP" instead of a 
        random code in 50% of CAPTCHA images.</span>
      </div>
    </form>
  </body>
</html>

Giải thích

Mã nguồn xác thực BotDetect CAPTCHA dùng Ajax được đặt trong script file BotDetectAjaxValidation.js phía máy khách. Vì chúng tôi sử dụng jQuery cho yêu cầu của Ajax, chúng tôi bao gồm cả hai script file cùng với file chuẩn. Nâng cấp lên phiên bản mới hơn của jQuery khá dễ dàng (chỉ việc tham chiếu tới phiên bản mới thay vì phải cài đặt lại). Hình ảnh và âm thanh CAPTCHA không cần phải thay đổi gì khi dùng Ajax để xác thực.

Việc xác thực CAPTCHA thực sự được thực thi từ hàm được gọi khi nhấn nút onclick trong ví dụ mẫu. Nó cũng có thể được xử lý trong hàm xử lý sự kiện onsubmit của trang, và nếu bạn thực hiện việc xác thực các trường khác phía máy khách bạn phải tích hợp lời gọi hàm này.

ProcessFormAjax.asp

Mã nguồn đầy đủ

<%
  'Captcha validation
  Dim result, codeKey, inputCode
  result = False
  codeKey = "LanapBotDetectCode"
  inputCode = Request("CaptchaCode")

  If (Session(codeKey)<>"") Then
    code = Session(codeKey)
    result = (0 = StrComp(inputCode, code, 1))
    'each Captcha code can only be validated once
    Session(codeKey) = ""
  End If

  If result = False Then
    first_name = Request("FirstName")
    last_name = Request("LastName")
    redirect_url = "BotDetectAjaxDemo.asp?FirstName=" + _ 
      first_name + "&LastName=" + last_name + "&WrongCode=WrongCode"
    Response.Redirect redirect_url
  End If
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
  <title>BotDetect CAPTCHA ASP Ajax Demo - Protected Page</title>
  <link type='text/css' rel='Stylesheet' href="FormStyle.css" />
</head>
<body>
  <form name="form1" method="post" id="form1" 
    action="ProcessForm.asp">
    <fieldset id="Properties">
      <legend>BotDetect CAPTCHA validation passed!</legend>
      <div class="input">
        <label for="FirstName">First Name:</label>
        <input name="FirstName" id="FirstName" type="text" 
          class="textbox" readonly="readonly" 
          value="<% =Request("FirstName") %>" />
      </div>
      <div class="input">
        <label for="LastName">Last Name:</label>
        <input name="LastName" id="LastName" type="text" 
        class="textbox" readonly="readonly" 
        value="<% =Request("LastName") %>" />
      </div>
    </fieldset>
    <div id="ActionDiv">
      <a href="BotDetectAjaxDemo.asp">Back to the sample form</a>
    </div>
  </form>
</body>
</html>

Giải thích

Mã nguồn xác thực phía máy chủ không thay đổi khi sử dụng xác thực phía máy khách bằng Ajax, vì vậy giải thích và ghi chú tương tự như Ví dụ xác thực CAPTCHA. Về cơ bản, vì việc xác thực phía máy khách chỉ là cải tiến thêm vào và không thể được dùng như là phương tiện để xác thực (vì nó không bảo mật và dễ bị bẻ gãy - như đã giải thích ở mục hỏi đáp), chúng tôi luôn luôn xác thực câu trả lời của người dùng trên phía máy chủ. Điều này là cần thiết để đảm bảo tính bảo mật của CAPTCHA.

LanapBotDetectHandler.asp

Mã nguồn đầy đủ

<%
Dim code, codeKey, codeHash, codeHashKey, captchaId, comCaptcha, _ 
  index, appCodeKey, captchaSessionIdKey

'the Captcha code is kept in Session state with this key
codeKey = "LanapBotDetectCode"
codeHashKey = "LanapBotDetectCodeHash"
captchaSessionIdKey = "LanapBotDetectID"

Function createGuid()
  Set TypeLib = Server.CreateObject("Scriptlet.TypeLib")
  tg = TypeLib.Guid
  guid = Left(tg, len(tg)-2)
  set regEx = New RegExp
  regEx.IgnoreCase = False
  regEx.Global = True
  regEx.Pattern = "[{}-]"
  createGuid = regEx.Replace(guid, "")
  Set TypeLib = Nothing
End Function

Function getCaptchaSessionID()
  Dim captchaSessionID
  If (Session(captchaSessionIdKey) <> "") Then
    captchaSessionID = Session(captchaSessionIdKey)
  Else
    captchaSessionID = createGuid()
    Session(captchaSessionIdKey) = captchaSessionID
  End If
  getCaptchaSessionID = captchaSessionID
End Function

'if there are multiple Captchas on tn the site, a Captcha id is 
'required to distinguish between them; otherwise, it can be ignored
captchaId = Request("CaptchaId")
If(captchaId<>"") Then
  codeKey = codeKey & "_" & captchaId
End If

If (Request("Command")="CreateImage") Then
'Captcha image generation

  'create the Captcha component instance
  Set comCaptcha = CreateObject("Lanap.BotDetect")

  'process Captcha properties
  If (Request("TextStyle")<>"") Then 'set Captcha algorithm
    On Error Resume Next
    comCaptcha.TextStyle = CLng(Request("TextStyle"))
    Err.Clear
  End If
  If (Request("ImageWidth")<>"") Then  'set Captcha image width
    On Error Resume Next
    comCaptcha.ImageWidth = CLng(Request("ImageWidth"))
    Err.Clear
  End If
  If (Request("ImageHeight")<>"") Then  'set Captcha image height
    On Error Resume Next
    comCaptcha.ImageHeight = CLng(Request("ImageHeight"))
    Err.Clear
  End If
  If (Request("CodeLength")<>"") Then  'set Captcha code length
    On Error Resume Next
    comCaptcha.CodeLength = CLng(Request("CodeLength"))
    Err.Clear
  End If
  If (Request("CodeType")<>"") Then  'set Captcha code type
    On Error Resume Next
    comCaptcha.CodeType = CLng(Request("CodeType"))
    Err.Clear
  End If
  If (Request("Format")<>"") Then  'set Captcha image format
    On Error Resume Next
    comCaptcha.Format = Request("Format")
    Err.Clear
  End If

  'set Captcha image Http response headers
  Response.Buffer = True
  Response.CacheControl = "no-cache, no-store, must-revalidate"
  Response.AddHeader "Pragma", "no-cache"
  Response.Expires = -1
  If (comCaptcha.Format="JPEG") Then
    Response.ContentType = "image/jpeg"
  ElseIf (comCaptcha.Format="PNG") Then
    Response.ContentType = "image/png"
  ElseIf (comCaptcha.Format="GIF") Then
    Response.ContentType = "image/gif"
  ElseIf (comCaptcha.Format="BMP") Then
    Response.ContentType = "image/bmp"
  End If

  'generate the Captcha image binary data
  Dim varPicture
  varPicture = comCaptcha.CreateImage

  'save the Captcha code for sound generation and validation
  code = comCaptcha.GetValue
  Session(codeKey) = code
  'save the code hash for backward compatibility with older validation 
  'code
  codeHash = comCaptcha.GetHashValue
  Session(codeHashKey) = codeHash

  'Chrome workaround
  index = InStr(Request.ServerVariables("HTTP_USER_AGENT"), "Chrome")
  If (index > 0) Then
    appCodeKey = getCaptchaSessionID() & codeKey
    Application.Lock
    Application(appCodeKey) = code
    Application.UnLock
    Response.Cookies(captchaSessionIdKey) = getCaptchaSessionID()
    Response.Cookies(captchaSessionIdKey).Expires = DateAdd("H", 1, Now)
    Response.Cookies(captchaSessionIdKey).Path = "/"
  End If

  'send Captcha image binary data to the client
  Response.BinaryWrite varPicture
  Set comCaptcha = Nothing  'dispose of the Captcha component instance
  Response.End
'end Captcha image generation

ElseIf (Request("Command")="CreateSound") Then
'audio Captcha generation

  'create the Captcha component instance
  Set comCaptcha = CreateObject("Lanap.BotDetect")

  'set Http response headers
  If ((Request.ServerVariables("HTTPS")="off") Or Request("e")="") Then
    Response.CacheControl = "no-cache"
    Response.AddHeader "Pragma", "no-cache"
    Response.Expires = -1
  End If
  Response.Buffer = True
  Response.ContentType = "audio/x-wav"
  If (Request("d") = "") Then
  Response.AddHeader "content-disposition", _
    "attachment; filename=captcha.wav"
  End If
  Response.AddHeader "Content-Transfer-Encoding", "binary"
  Response.AddHeader "Connection", "Close"

  'generate the audio Captcha binary data from the saved code
  code = Session(codeKey)
  If (Request("s") <> "") Then  'Chrome workaround
    appCodeKey = Request("s") & codeKey
    code = Application(appCodeKey)
  End If
  varSound = comCaptcha.CreateSoundFromCode(code)

  'send audio Captcha binary data to the client
  Response.BinaryWrite varSound
  Set comCaptcha = Nothing 'dispose of the Captcha component instance
  Response.End
'end audio Captcha generation

ElseIf (Request("Command")="Validate") Then
'Ajax Captcha validation

  Dim result
  result = False

  If (Session(codeKey)<>"") Then
    Dim inputCode
    inputCode = Request("Code")
    code = Session(codeKey)
    result = (0 = StrComp(inputCode, code, 1))
    'Ajax validation shouldn't remove the code if successful, so both 
    'client- and server-side validation can be performed and pass
    If (Not result) Then
      Session(codeKey) = ""
    End If
  End If

  'Http response headers
  Response.Buffer = True
  Response.ContentType = "text/javascript"
  Response.CacheControl = "no-cache, no-store, must-revalidate"
  Response.AddHeader "Pragma", "no-cache"
  Response.Expires = -1
  Response.AddHeader "Connection", "Close"

  'send the JSON validation result to the client
  Response.Write "{ 'result': " & LCase(CStr(result)) & " }"
  Response.End

'end Ajax Captcha validation
End If

'If neither of the above conditions was met
Response.Status = "400 Bad Request"
Response.End
%>

Giải thích

Giao tiếp Http được sử dụng cho việc xác thực CAPTCHA bằng Ajax được bao gồm trong file LanapBotDetectHandler.asp. Nó được truy cập qua Url như LanapBotDetectHandler.asp?Command=Validate&Code=ABCDE, và trả về kết quả bằng định dạng JSON đơn giản ( { 'result': true } hoặc { 'result': false } ).

Sự khác biệt quan trọng duy nhất khi xác thực CAPTCHA bằng Ajax là khi người sử dụng nhập câu trả lời đúng, chúng ta không xoá dữ liệu đúng từ trạng thái Session. Bằng cách đó, cùng một câu trả lời có thể được xác thực hai lần (lần đàu ở phía máy khách và lần thứ hai ở phía máy chủ khi toàn trang được gửi). Dĩ nhiên, câu trả lời được xoá trong quá trình xác thực ở phía máy chủ.

Khi việc xác thực CAPTCHA thất bại, chúng ta cũng xoá / thay đổi ký tự CAPTCHA. Nếu không bots có thể sử dụng để tấn công liên tục trên cùng một hình ảnh CAPTCHA, cho phép nhiều lần xác thực trên cùng một ký tự. Điều này có lẽ sẽ trở thành lỗ hổng bảo mật của CAPTCHA, vì vậy câu trả lời cần phải được xoá khi việc xác thực bằng Ajax bị thất bại.

BotDetectScript.js

Mã nguồn đầy đủ

function LBD_LoadSound(soundPlaceholderId, soundLink) {
  if(document.getElementById) {
    var i = soundLink.indexOf('&d=');
    if (-1 != i) {
      soundLink = soundLink.substring(0, i);
    }
    soundLink = soundLink + '&d=' + LBD_GetTimestamp();
		
    if ( (-1 == soundLink.indexOf('&e=')) && 
         (document.location.protocol == "https:")) {
      soundLink = soundLink + '&e=1';
    }

    cid = LBD_GetCookie("LanapBotDetectID");
    if (cid) {
      soundLink = soundLink + '&s=' + cid;
    }

    var placeholder = document.getElementById(soundPlaceholderId);
    var objectSrc = "<object id='captchaSound' 
      classid='clsid:22D6F312-B0F6-11D0-94AB-0080C74C7E95' 
      height='0' width='0' style='width:0; height:0;'><param 
      name='AutoStart' value='1' /><param name='Volume' value='0' 
      /><param name='PlayCount' value='1' /><param name='FileName' 
      value='" + soundLink + "' /><embed id='captchaSoundEmbed' 
      src='"+ soundLink + "' autoplay='true' hidden='true' 
      volume='100' type='"+ LBD_GetMimeType() +"' 
      style='display:inline;' /></object>";

    placeholder.innerHTML = "";
    placeholder.innerHTML = objectSrc;
  }
}

function LBD_GetTimestamp() {
  var d = new Date();
  var t = d.getTime() + (d.getTimezoneOffset() * 60000);
  return t;
}

function LBD_GetMimeType() {
  var mimeType = "audio/x-wav";
  return mimeType;
}

var LBD_ImgId = null;
var LBD_Img = null;
var LBD_NewImg = null;
var LBD_Parent = null;
var LBD_ImagePrompt = null;

function LBD_ReloadImage(imgId) {
  if(imgId) {
    LBD_ImgId = imgId;
    LBD_Img = document.getElementById(LBD_ImgId);
    var src = LBD_Img.src;

    var i = src.indexOf('&d=');
    if (-1 != i) {
      src = src.substring(0, i);
    }
    var newSrc = src + '&d=' + LBD_GetTimestamp();

    LBD_NewImg = document.createElement('img');
    LBD_NewImg.onload = LBD_ShowImage;
    LBD_NewImg.id = LBD_Img.id;
    LBD_NewImg.alt = LBD_Img.alt;
    LBD_NewImg.src = newSrc;

    LBD_ImagePrompt = document.createElement('span');
    LBD_ImagePrompt.appendChild(document.createTextNode('loading...'));

    LBD_Parent = LBD_Img.parentNode;
    LBD_Parent.removeChild(LBD_Img);
    LBD_Parent.appendChild(LBD_ImagePrompt);
  }
}

function LBD_ShowImage() {
  if(LBD_NewImg && LBD_Parent && LBD_ImagePrompt) {
    LBD_Parent.removeChild(LBD_ImagePrompt);
    LBD_Parent.appendChild(LBD_NewImg);
  }
}

function LBD_GetCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') {
      c = c.substring(1, c.length);
    }
    if (c.indexOf(nameEQ) == 0) {
      return c.substring(nameEQ.length, c.length);
    }
  }
  return null;
}

Giải thích

Đây là script chuẩn ở phía máy khách dùng để phát âm thanh và tạo hình ảnh CAPTCHA, cũng được sử dụng bởi Ajax CAPTCHA, mà không cần thay đổi nào so với khi sử dụng không dùng Ajax.

BotDetectAjaxValidation.js

Mã nguồn đầy đủ

// element identifiers 
var captchaImageId = 'SampleForm_CaptchaImage';
var codeTextboxId = 'CaptchaCode';
var errorLabelId = 'CodeIncorrectLabel';
var formId = 'SampleForm';

// other settings
var validationPrompt = 'validating...';
var ajaxTimeoutmilliseconds = 5000;

// shared variable declarations
var LBD_ValidationResult = false;
var LBD_ValidationRequest = null;
var LBD_CodeInput = null;
var LBD_ValidationPrompt = null;
var LBD_ErrorPrompt = null;
var LBD_PromptParent = null;

function LBD_Validate(captchaId) 
{
  if(!LBD_ValidationResult) 
  { // only validate the CAPTCHA if it isn't already passed
  
    // init elements
    LBD_CodeInput = document.getElementById(codeTextboxId);
    LBD_ErrorPrompt = document.getElementById(errorLabelId);
    LBD_PromptParent = LBD_ErrorPrompt.parentNode;
    
    if(!LBD_CodeInput || !LBD_CodeInput.value || 
      LBD_CodeInput.value.length < 0) 
    { // validation fails if there is no user input
      LBD_EndValidation(false);
      LBD_CodeInput.focus();
    } 
    else 
    { // Ajax validation
      LBD_StartValidation(captchaId);
    }
  }
  return LBD_ValidationResult;
}

function LBD_StartValidation(captchaId) 
{
  // hide the error message
  LBD_ErrorPrompt.style.visibility = 'hidden';
  
  // show the validation status indicator
  LBD_ValidationPrompt = document.createElement('span');
  LBD_ValidationPrompt.id = 'LBD_ValidatingPrompt';
  LBD_ValidationPrompt.appendChild(document.createTextNode(
    validationPrompt));
  LBD_PromptParent.appendChild(LBD_ValidationPrompt);

  // send the user input to the server for validation
  LBD_ValidateCode(captchaId, LBD_CodeInput.value, LBD_EndValidation);
}

function LBD_ValidateCode(captchaId, code, callback) 
{
  // set Ajax request timeout threshold
  $.ajaxSetup( { 
    timeout : ajaxTimeoutmilliseconds
  } );
  
  // send CAPTCHA validation request
  if (!captchaId) {
    LBD_ValidationRequest = $.getJSON( 
        // server path
      "LanapBotDetectHandler.asp", 
        // querystring params
      { Command: "Validate", Code: code }, 
        // callback function
      function(json) { LBD_ProcessValidationResult(json.result, 
        callback) } 
    );
  } else {
    LBD_ValidationRequest = $.getJSON( 
        // server path
      "LanapBotDetectHandler.asp", 
        // querystring params
      { Command: "Validate", Code: code, CaptchaId: captchaId }, 
        // callback function
      function(json) { LBD_ProcessValidationResult(json.result, 
        callback) } 
    );
  }
  
  // if Ajax CAPTCHA validation timeouts, fall back to full 
  // form postback
  $("#" + formId).ajaxError(function(LBD_ValidationRequest, 
    settings, err) { 
    LBD_PromptParent.removeChild(LBD_ValidationPrompt);
    this.submit(); 
  });
}

function LBD_ProcessValidationResult(result, callback) 
{ 
  // when the validation result arrives, remove validation status 
  // indicator
  LBD_PromptParent.removeChild(LBD_ValidationPrompt);

  if(!result) 
  { // CAPTCHA validation failed, reset the CAPTCHA
    LBD_ReloadImage(captchaImageId);
    LBD_CodeInput.value = '';
  }

  if ("function" == typeof(callback)) 
  { // invoke the registered callback function
    callback(result);
  }
}

function LBD_EndValidation(result) 
{
  if(result) 
  { // CAPTCHA validation passed, submit the form to the server
    LBD_ErrorPrompt.style.visibility = 'hidden';
    LBD_ValidationResult = true;
    document.getElementById(formId).submit();
  } 
  else
  { // CAPTCHA validation failed, show error message
    LBD_ErrorPrompt.style.visibility = 'visible';
  }
}

Giải thích

Mục đích chủ yếu của xác thực CAPTCHA dùng Ajax là trả lời người dùng ngay lập tức khi họ nhập sai câu trả lời, mà không làm ảnh hưởng đến phần còn lại của trang. Vì vậy chúng ta sử dụng script này để xử lý câu trả lời của người dùng, và nếu việc xác thực thành công toàn trang sẽ được gửi như thông thường (do vậy, chúng ta thay đổi cách tương tác với người dùng, mà không làm giảm tính bảo mật khi đối phó với bots).

Điều này tăng tính dễ sử dụng khi người dùng nhập câu trả lời sai, đổi lại chúng ta phải xác thực hai lần khi người dùng nhập câu trả lời đúng. Vì ích lợi của sự trả giá này được người sử dụng chấp nhận, trong khi cái giá chỉ ảnh hưởng đến mã nguồn, sự thay đổi này cũng đáng công sức. Hơn nữa, xử lý trường hợp bị lỗi (như khi nhập câu trả lời sai) có ảnh hưởng lớn hơn trên tính khả dụng tổng quát (vì lỗi thương làm người dùng chán nản), nên đó là một ý hay để làm trơn tru quá trình hoạt động của trang web.

Tên của các thành tố sử dụng bởi việc xác thực CAPTCHA bằng Ajax được khai báo ở phần đầu của script, vì vậy bạn phải thay đổi tương ứng nếu bạn sử dụng tên khác cho các thành tố.

Bắt đầu quá trình xác thực trên phía máy khách chúng tôi kiểm tra liệu có tồn tại câu trả lời hay không – nếu người sử dụng chưa hề nhập ký tự nào, chúng ta không phải gọi lại máy chủ để biết kết quả xác thực. Như được định nghĩa trong hàm LBD_EndValidation, khi xác thực CAPTCHA thất bại chúng ta hiển thị thông báo lỗi; nếu thành công chúng ta tắt thông báo lỗi và gửi toàn bộ trang lên máy chủ.

Vì việc xác thực CAPTCHA được thực hiện không đồng bộ, có các hàm riêng biệt để xử lý sự bắt đầu của hàm gọi lại và sự trả lời từ máy chủ. Trước khi gửi yêu cầu xác thực chúng ta hiển thị câu thông báo đơn giản ("đang xác thực..."), câu này được thay thế bằng kết quả xác thực khi máy chủ gửi về. Lệnh gọi jQuery để thực thi yêu cầu của Ajax được tô đậm. Ví dụ này chỉ sử dụng việc xử lý lỗi cơ bản. Tuỳ thuộc vào cách xử lý lỗi và xác thực phía máy khách của bạn, bạn có thể thay đổi script file này cho phù hợp.

FormStyle.css

Mã nguồn đầy đủ

body {
  background-color: #EEEEFF;
  font-family: Verdana, Arial;
  font-size: 0.9em;
}

fieldset {
  padding: 0 10px 10px 10px;
  margin: 11px;
  width: 300px;
  display: block;
}

div.input {
  margin: 7px 0;
}

legend {
  padding: 5px;
  color: #999999;
}

label {
  display: block;
  width: 85px;
  float: left;
  text-align: right;
  padding-right: 5px;
}

input.textbox {
  width: 170px;
}

input.textboxSmall {
  width: 40px;
}

#CodeIncorrectLabel {
  color: Red;
}

#CodeCorrectLabel {
  color: Green;
}

#Note {
  padding: 0;
  margin: 11px;
  margin-bottom: -7px;
  width: 320px;
  font-size: 0.8em;
  color: Red;
}

#PromptDiv {
  padding: 0;
  margin: 0;
  margin-bottom: 8px;
}

#ActionDiv {
  padding: 0 0 10px 10px;
  margin: 11px;
  margin-right: 0;
  width: 314px;
  text-align:right;
}

fieldset #ActionDiv{
  padding: 0;
  margin: 0;
  width: auto;
  text-align:right;
}

#CaptchaDiv {
  margin: 0;
  padding: 0;
  width:265px;
  height:50px;
  padding-bottom: 5px;
}

#CaptchaImage {
  float: left;
  margin: 0;
  padding: 0;
  width:240px;
  height:50px;
}

#CaptchaIcons {
  width: 22px;
  height: 50px;
  float: right;
  text-align: left;
  margin: 0;
  padding: 0;
}

td#CaptchaIcons {
  padding-left: 3px;
}

#CaptchaIcons img {
  border: 0;
  margin: 0;
  padding: 0;
  padding-bottom: 3px;
}

*html #CaptchaIcons img {
  margin-bottom: -2px;
}

.placeholder {
  visibility: hidden;
  width:0 !important;
  height:0 !important;
}

*html .placeholder {
  display: none !important;
}

#CaptchaPreviewDiv {
  margin: 0;
  padding: 0;
  padding-bottom: 5px;
}

div.FeaturesInput {
  margin: 7px 0;
}

div.FeaturesInput label {
  width: 110px;
}

Giải thích

Định nghĩa style được sử dụng trong ví dụ này giống như trong ví dụ xác thực CAPTCHA.

Phiên bản hiện tại của BotDetect

Xin lưu ý

Trang này là bản dịch tiếng Việt không chính thức của trang gốc tiếng Anh: BotDetect CAPTCHA Ajax Validation ASP Code Sample và có thể không chính xác, không đầy đủ hoặc không cập nhật.

Cập nhật ngày 2009-11-30. Áp dụng cho BotDetect ASP.NET CAPTCHA v2.0.15 và BotDetect ASP CAPTCHA v2.0.9.

language: English Español Tiếng Việt