我想向CreateUserWizard添加一個「反機器人」問題,作爲Captcha控件更易於使用的替代方案。我對asp相當陌生,並發現我有點陷入了WinForms的心態。不過,我已經想出了一些似乎可行的東西。向CreateUserWizard添加「反機器人」增強功能
標記:
<asp:CreateUserWizard ID="CreateUserWizard1" runat="server">
.
.
<tr>
<td align="right">
<asp:Label ID="AntiRobotQuestion" runat="server" AssociatedControlID="AntiRobotAnswer">
Question:
</asp:Label>
</td>
<td>
<asp:TextBox ID="AntiRobotAnswer" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="AntiRobotAnswerRequired" runat="server" ControlToValidate="AntiRobotAnswer" ErrorMessage="Answer is required." ToolTip="Answer is required." ValidationGroup="CreateUserWizard1">
</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td align="center" colspan="2" style="color:Red;">
<asp:Literal ID="CustomErrorMessage" runat="server" Visible="False" EnableViewState="False"></asp:Literal>
</td>
</tr>
.
.
</asp:CreateUserWizard>
後面的代碼:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) {
//Set up the Anti-Robot Question and Answer
Label robotQuestion = (Label)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("AntiRobotQuestion");
//Simulate randomly selecting a question and answer from a database table...
robotQuestion.Text = "What is the capital of France";
Session["AntiRobotAnswer"] = "Paris";
}
}
protected void CreateUserWizard1_CreatingUser(object sender, LoginCancelEventArgs e)
{
//Check the anti-robot Q & A
TextBox robotAnswer = (TextBox)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("AntiRobotAnswer");
if (robotAnswer.Text != (string)Session["AntiRobotAnswer"])
{
Literal errorMessage = (Literal)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("CustomErrorMessage");
errorMessage.Text = "Wrong answer! Are you a robot?";
errorMessage.Visible = true;
e.Cancel = true;
}
}
這是實現代碼能夠接受的方式?有兩件事對我來說看起來有點「不整潔」:
- 使用FindControl拉出標記中控件的引用。
- 將預期答案存儲在會話變量中。 (它有多安全?)
編輯(2012-01-23) 已經給出了一些有效的設計替代方案。然而,我有一個合理的理由來使用這個問題和答案技術(可能除了蜜罐的想法之外)。例如,與論壇主題相關的問題可以幫助防止垃圾郵件發送者和機器人。問題是:上面列出的代碼是否可以接受?從WinForms背景來看,它對我來說看起來有點笨重 - 但也許這就是asp應該看起來的樣子。
另一種選擇到許多其他的想法會話變量是在ViewState/ControlState中存儲答案的* hash *。我說存儲散列,而不是答案,因爲ViewState並不總是完全加密,但*應該*總是防止通過[ViewState MAC]篡改(http://www.testingreflections.com/node/view/3424 )(當然一些愚蠢的人可能已經禁用了...) – 2012-01-18 23:50:58
我不喜歡這個想法...更好地使蜜罐驗證碼http://haacked.com/archive/2007/09/11/honeypot-captcha。 aspx – Aristos 2012-01-18 23:55:54
我喜歡這兩種替代想法。 – Fruitbat 2012-01-20 00:02:54