将自定义视图模型与隐藏表单域结合使用。只要确保它全部通过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