Mã nguồn ví dụ mẫu xác thực BotDetect ASP.NET 1.1 CAPTCHA - VB.NET

Ví dụ xác thực BotDetect ASP.NET CAPTCHA chứa mã cơ bản cần thiết để thêm CAPTCHA vào trang ASP.NET và xác thực câu trả lời của người dùng. Nó có thể dùng như điểm bắt đầu nếu đây là lần đầu tiên bạn học cách sử dụng BotDetect CAPTCHA, và nó tương đương với kết quả bạn đạt được nếu làm theo hướng dẫn Sử dụng BotDetect ASP.NET CAPTCHA trong Visual Studio 2003.

Vị trí dự án mẫu

Mặc định, dự án mẫu này được cài đặt tại
C:\Program Files\Lanapsoft\BotDetect\ASP.NET 1.1\v2.0\Samples\VBNetBotDetect2Demo\.

Bạn cũng có thể chạy nó từ Start Menu:
Programs > Lanapsoft > BotDetect > ASP.NET 1.1 > v2.0 > Samples > VB.NET BotDetect CAPTCHA ValidationSample.

Default.aspx

Mã nguồn đầy đủ

<%@ Page Language="vb" AutoEventWireup="false"
  Codebehind="Default.aspx.vb" Inherits="VBNetBotDetectDemo._Default" 
%>

<%@ Register Assembly="Lanap.BotDetect" Namespace="Lanap.BotDetect" 
  TagPrefix="BotDetect" %>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>BotDetect Demo</title>
    <link type='text/css' rel='Stylesheet' href="StyleSheet.css" />
</head>
<body>
    <form id="form1" runat="server">
    <fieldset id="Preview">
        <legend>
            <span id="PreviewLegend">CAPTCHA Preview</span>
        </legend>
        <div id="PromptDiv">
            <span id="Prompt">Type the characters you see in 
              the picture</span>
        </div>
        <div id="CaptchaDiv">
            <BotDetect:Captcha ID="SampleCaptcha" runat="server" />
        </div>
        <div id="ValidationDiv">
            <asp:TextBox ID="CodeTextBox" runat="server">
            </asp:TextBox>
            <asp:Button ID="ValidateButton" runat="server" />
            <asp:Label ID="MessageCorrectLabel" runat="server">
            </asp:Label>
            <asp:Label ID="MessageIncorrectLabel" runat="server">
            </asp:Label>
        </div>
    </fieldset>
    <div id="Note">
        <span>NOTE: the Trial version will use "LANAP" instead of a 
          random code in 50% of renderings.</span>
    </div>
    </form>
</body>
</html>

Giải thích

Những dòng cần thiết để thêm BotDetect CAPTCHA vào trang ASP.NET và thực hiện việc xác thực sử dụng Ajax được tô đậm. Để sử dụng <BotDetect:Captcha>, trước hết chúng ta phải đăng ký Lanap.BotDetect.dll sử dụng <%@Register %>.

Trang web còn chứa <asp:TextBox> để người dùng nhập câu trả lời, một <asp:Button> để gửi câu trả lời, và một cặp <asp:Label> dùng để hiển thị kết quả xác thực.

.

Phần còn lại của file được sinh ra bởi Visual Studio 2003, hoặc dùng để định nghĩa cách thức sắp xếp và hiển thị của trang.

Default.aspx.vb

Mã nguồn đầy đủ

	Public Class _Default
    Inherits System.Web.UI.Page

    #Region " Web Form Designer Generated Code "

    'This call is required by the Web Form Designer.
    <System.Diagnostics.DebuggerStepThrough()> Private Sub _
        InitializeComponent()
    End Sub
    
    Protected WithEvents MessageCorrectLabel As _
        System.Web.UI.WebControls.Label
				
    Protected WithEvents MessageIncorrectLabel As _
        System.Web.UI.WebControls.Label
				
    Protected WithEvents SampleCaptcha As _
        Lanap.BotDetect.Captcha
				
    Protected WithEvents CodeTextBox As _
        System.Web.UI.WebControls.TextBox
				
    Protected WithEvents ValidateButton As _
        System.Web.UI.WebControls.Button

    'NOTE: The following placeholder declaration is required by 
    'the Web Form Designer. Do not delete or move it.
    Private designerPlaceholderDeclaration As System.Object

    Private Sub Page_Init(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles MyBase.Init
        'CODEGEN: This method call is required by the Web Form 
        'Designer. Do not modify it using the code editor.
        InitializeComponent()
    End Sub

    #End Region

    Protected Sub Page_PreRender(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles MyBase.PreRender

        ' initial page setup
        If (Not IsPostBack) Then

            'set control text
            ValidateButton.Text = "Validate"
            MessageCorrectLabel.Text = "Correct!"
            MessageIncorrectLabel.Text = "Incorrect!"

            'these messages are shown only after validation
            MessageCorrectLabel.Visible = False
            MessageIncorrectLabel.Visible = False
        End If        ' clear user input on Reload button clicks
        Dim scriptTemplate As String
        scriptTemplate = "<script type='text/javascript'>" & _
          "function LBD_ClearUserInput() {{" & _
          "  var LBD_textBox = document.getElementById('{0}');" & _
          "  if(LBD_textBox) {{" & _
          "    LBD_textBox.value = '';" & _
          "  }}" & _
          "}}" & _
          "LBD_RegisterHandler('PreReloadCaptchaImage', _
            LBD_ClearUserInput);</script>"

        Dim script As String
        script = String.Format(scriptTemplate, CodeTextBox.ClientID)
        If (Not Page.ClientScript.IsStartupScriptRegistered( _
            "CaptchaReloadClearInput")) Then
          Page.ClientScript.RegisterStartupScript(Me.GetType(), _ 
            "CaptchaReloadClearInput", script, True)
        End If
				
        ' automatically lowercase user input
				
        CodeTextBox.Attributes.Add("onkeyup", _
            "this.value = this.value.toLowerCase();")

        If (IsPostBack) Then
            'validate the input code, and show the 
            'appropriate message 
            Dim code As String = CodeTextBox.Text.Trim().ToUpper()

            If (SampleCaptcha.Validate(code)) Then
                MessageCorrectLabel.Visible = True
                MessageIncorrectLabel.Visible = False
            Else
                MessageCorrectLabel.Visible = False
                MessageIncorrectLabel.Visible = True
            End If

            'clear previous user code input
            CodeTextBox.Text = ""
        End If

    End Sub

End Class

Giải thích

Việc xử lý trang được thực hiện trong phương thức xử lý sự kiện Page_PreRender, vì vậy tất cả các sự kiện được thực thi trước khi xác thực CAPTCHA. Nếu bạn muốn xác thực CAPTCHA trước một sự kiện nào đó, bạn có thể di chuyển đoạn mã xử lý vào phương thức Page_Load.

Hơn nữa, việc xử lý không được thực hiện trong phương thức ValidateButton_Click là có chủ đích, trong trường hợp có nhiều controls gửi trang – chúng ta muốn xác thực CAPTCHA cho dù vấn đề gì xảy ra. Hầu hết các bots sẽ không gửi trang bằng cách click vào nút, mà bằng cách dùng POST, có thể có hoặc không bao gồm "control gây nên postback", có nhiệm vụ phát động sự kiện click nút. Kiểm tra CAPTCHA trên từng trang đảm bảo tính bảo mật trong tất cả các trường hợp.

Lần đầu tiên tải trang ( if (!IsPostBack) ), nút và nhãn được khởi động, và việc xác thực được bỏ qua, vì người dùng chưa trả lời nó.

Mỗi lần trang được tải, chúng ta thêm một đoạn JavaScript nhỏ vào textbox hàm xử lý sự kiện phía máy khách onkeyup, vì vậy câu trả lời của người dùng ngay lập tức bị đổi thành chữ thường. Nó có mục đích để người sử dụng hiểu rằng CAPTCHA không phân biệt hoa hay thường.

Thêm nữa, chúng ta đăng ký một hàm xử lý sự kiện chạy trên máy khách PreReloadCaptchaImage để tự động xóa câu trả lời của người dùng mỗi lần tải lại trang. Vì khi nhấn nút Reload sẽ thay đổi ngẫu nhiên ký tự CAPTCHA, điều này giúp người dùng không phải xóa từng ký tự họ đã gõ vào trước khi thay đổi mã.

Khi trang được gửi ( if (IsPostBack) ), chúng ta gửi câu trả lời của người dùng vào phương thức Captcha.Validate(). Ở trong ví dụ này chúng ta dùng kết quả xác thực chỉ để hiển thị một thông báo, và luôn luôn hiển thị CAPTCHA mới. Trong hầu hết mọi trường hợp, bạn sẽ hiển thị CAPTCHA mới chỉ khi người dùng trả lời sai trước đó, và thực thi đoạn mã được bảo vệ (đăng nhập, comment...) nếu CAPTCHA được trả lời đúng.

Nếu bạn dẫn người dùng tới một trang khác khi xác thực thành công, và bạn muốn bảo vệ trang đó, có thể là ý hay khi dùng biến Session (ví dụ, Session["IsHuman"] = true), và kiểm tra trên các trang tiếp theo. Nếu không, bots có thể được viết để bỏ qua trang bảo vệ và truy cập trực tiếp vào trang được bảo vệ.

Cuối cùng, vì hình ảnh CAPTCHA được hiển thị mới mỗi lần trang được tải và mỗi mã CAPTCHA chỉ có thể được xác thực một lần (bất chấp kết quả xác thực), câu trả lời của người dùng phải được xoá sau khi xác thực.

Web.config

Mã nguồn đầy đủ

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    
  <system.web>
  
  <httpHandlers>
    <add verb="*" path="LanapCaptcha.aspx" 
      type="Lanap.BotDetect.CaptchaHandler, Lanap.BotDetect"/>
  </httpHandlers>

  <!--  DYNAMIC DEBUG COMPILATION
    Set compilation debug="true" to enable ASPX debugging. Otherwise, 
    setting this value to false will improve runtime performance of 
    this application. Set compilation debug="true" to insert debugging 
    symbols (.pdb information) into the compiled page. Because this 
    creates a larger file that executes more slowly, you should set 
    this value to true only when debugging and to false at all other 
    times. For more information, refer to the documentation about 
    debugging ASP.NET files.
  -->
  <compilation 
    defaultLanguage="vb"
    debug="false"
  />

  <!--  CUSTOM ERROR MESSAGES
    Set customErrors mode="On" or "RemoteOnly" to enable custom error 
    messages, "Off" to disable. 
		
    Add <error> tags for each of the errors you want to handle.

    "On" Always display custom (friendly) messages.
		
    "Off" Always display detailed ASP.NET error information.
		
    "RemoteOnly" Display custom (friendly) messages only to users not 
      running on the local Web server. This setting is recommended for 
      security purposes, so that you do not display application detail 
      information to remote clients.
  -->
  <customErrors 
    mode="RemoteOnly" 
  /> 

  <!--  AUTHENTICATION 
    This section sets the authentication policies of the application. 
    Possible modes are "Windows", "Forms", "Passport" and "None".

    "None" No authentication is performed. 
		
    "Windows" IIS performs authentication (Basic, Digest, or 
    Integrated Windows) according to its settings for the 
    application. Anonymous access must be disabled in IIS. 
		
    "Forms" You provide a custom form (Web page) for users to 
    enter their credentials, and then you authenticate them 
    in your application. A user credential token is stored 
    in a cookie.
		
    "Passport" Authentication is performed via a centralized 
    authentication service provided by Microsoft that offers 
    a single logon and core profile services for member sites.
  -->
  <authentication mode="Windows" /> 

  <!--  AUTHORIZATION 
    This section sets the authorization policies of the 
    application. You can allow or deny access to application 
    resources by user or role. Wildcards: "*" mean everyone, 
    "?" means anonymous (unauthenticated) users.
  -->

  <authorization>
    <allow users="*" /> <!-- Allow all users -->
    <!-- 
    <allow users="[comma separated list of users]"
      roles="[comma separated list of roles]"/>
    <deny users="[comma separated list of users]"
      roles="[comma separated list of roles]"/>
    -->
  </authorization>

  <!--  APPLICATION-LEVEL TRACE LOGGING
    Application-level tracing enables trace log output for 
    every page within an application. 
    Set trace enabled="true" to enable application trace 
    logging. If pageOutput="true", the trace information 
    will be displayed at the bottom of each page. Otherwise, 
    you can view the application trace log by browsing the 
    "trace.axd" page from your web application root. 
  -->
  <trace
    enabled="false"
    requestLimit="10"
    pageOutput="false"
    traceMode="SortByTime"
    localOnly="true"
  />

  <!--  SESSION STATE SETTINGS
    By default ASP.NET uses cookies to identify which requests 
    belong to a particular session. If cookies are not available, 
    a session can be tracked by adding a session identifier to the 
    URL. To disable cookies, set sessionState cookieless="true".
  -->
  <sessionState 
    mode="InProc"
    stateConnectionString="tcpip=127.0.0.1:42424"
    sqlConnectionString="data source=127.0.0.1;Trusted_Connection=yes"
    cookieless="false" 
    timeout="20" 
  />

  <!--  GLOBALIZATION
    This section sets the globalization settings of the application. 
  -->
  <globalization 
    requestEncoding="utf-8" 
    responseEncoding="utf-8" 
  />
   
 </system.web>

</configuration>

Giải thích

Những dòng cần thiết để BotDetect CAPTCHA hoạt động đúng được tô đậm, các dòng khác đều được sinh ra bởi Visual Studio 2003.

Thành tố <httpHandlers> đăng ký đường dẫn sử dụng cho hình ảnh và âm thanh CAPTCHA được xử lý bởi mã trong Lanap.BotDetect.dll, trong khi thành tố <sessionState> khai báo cơ chế lưu trữ được sử dụng bởi BotDetect để lưu mã CAPTCHA và thiết lập cho mỗi người dùng.

Bạn có thể dùng các thiết lập Session State khác nhau tuỳ thuộc vào nhu cầu ứng dụng của bạn, nhưng bạn phải chắc chắn rằng Session State persistence sẵn sàng để BotDetect có thể hoạt động. Cần để ý nếu bạn sử dụng nhiều máy chủ load-balanced, như được giải thích trong mục hỏi đáp này.

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 ASP.NET 1.1 CAPTCHA Validation VB.NET 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