將自定義視圖模型與隱藏表單域結合使用。只要確保它全部通過https完成。
視圖模型
public LoginForm
{
public string UserName { get; set; }
public string Password { get; set; }
public int SecretQuestionId { get; set; }
public string SecretQuestion { get; set; }
public string SecretQuestionAnswer { get; set; }
}
操作方法
public ActionResult Login()
{
var form = new LoginForm();
return View(form);
}
[HttpPost]
public ActionResult Login(LoginForm form)
{
if (form.SecretQuestionId == 0)
{
//This means that they've posted the first half - Username and Password
var user = AccountRepository.GetUser(form.UserName, form.Password);
if (user != null)
{
//Get a new secret question
var secretQuestion = AccountRepository.GetRandomSecretQuestion(user.Id);
form.SecretQuestionId = secretQuestion.Id;
form.SecretQuestion = secretQuestion.QuestionText;
}
}
else
{
//This means that they've posted from the second half - Secret Question
//Re-authenticate with the hidden field values
var user = AccountRepository.GetUser(form.UserName, form.Password);
if (user != null)
{
if (AccountService.CheckSecretQuestion(form.SecretQuestionId, form.SecretQuestionAnswer))
{
//This means they should be authenticated and logged in
//Do a redirect here (after logging them in)
}
}
}
return View(form);
}
查看
<form>
@if (Model.SecretQuestionId == 0) {
//Display input for @Model.UserName
//Display input for @Model.Password
}
else {
//Display hidden input for @Model.UserName
//Display hidden input for @Model.Password
//Display hidden input for @Model.SecretQuestionId
//Display @Model.SecretQuestion as text
//Display input for @Model.SecretQuestionAnswer
}
</form>
如果你不快樂與發送將用戶名和密碼返回到隱藏字段中的視圖以重新進行身份驗證,並確保它們不是作弊......您可以創建一個HMAC或類似的測試項目。
順便說一句,這個問題似乎像一個問題彙集到一個...所以剛剛回答瞭如何做一個視圖/操作方法的兩步驗證。
對不起,如果它是多個問題,我只是想提供圍繞約束的最大細節。這絕對解決了我的問題,謝謝! – 2011-05-24 19:51:09