ASP.net mvc远程验证,它安全吗?怎么安全?

时间:2011-11-18 21:02:55

标签: asp.net-mvc

我最近在asp.net mvc中遇到了远程验证。真的有用的功能,但没有添加这样的东西到注册表,比如检查用户名或电子邮件,打开一个安全漏洞?有人用这个来从网站上挖掘信息吗? Captca是这个问题的一个明显的解决方案,但有没有人能够将它与[Remote]验证集成?

public class CreateUserModel : EditUserModel {
    [Required]
    [StringLength(6, MinimumLength = 3)]
    [Remote("IsUID_Available", "Validation")]
    [RegularExpression(@"(\S)+", ErrorMessage = "White space is not allowed.")]
    [Editable(true)]
    public override string UserName { get; set; }
}  

1 个答案:

答案 0 :(得分:1)

如果你愿意,可以使用Captcha。例如,使用Google的ReCaptcha,您可以安装microsoft-web-helpers NuGet,注册ReCaptcha account以获取私钥/公钥对,然后只需修改您的视图模型,以便在执行远程调用时包含2个附加字段:

public class CreateUserModel : EditUserModel 
{
    [Required]
    [StringLength(6, MinimumLength = 3)]
    [Remote("IsUID_Available", "Validation", AdditionalFields = "recaptcha_response_field,recaptcha_challenge_field", HttpMethod = "POST")]
    [RegularExpression(@"(\S)+", ErrorMessage = "White space is not allowed.")]
    [Editable(true)]
    public override string UserName { get; set; }
}

并在视图中:

@using Microsoft.Web.Helpers
@model CreateUserModel
@{
    ReCaptcha.PublicKey = "... public key obtained from Google ...";
}

<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>

@using (Html.BeginForm())
{
    @Html.EditorFor(x => x.UserName)
    @Html.ValidationMessageFor(x => x.UserName)
    @ReCaptcha.GetHtml(theme: "red")
    <button type="submit">OK</button>
}

并在控制器中:

[HttpPost]
public ActionResult IsUID_Available(string username)
{
    if (!ReCaptcha.Validate(privateKey: "... private key obtained from Google ..."))
    {
        return Json("sorry, please enter a correct Captcha first");
    }

    // TODO: the user entered a correct Captcha => you can proceed
    // into usrname existence verification:
    bool userExists = _repository.UserExists(username);
    return Json(userExists);
}