ASP.NET MVC3的最简单身份验证

时间:2011-11-19 11:03:20

标签: asp.net asp.net-mvc-3 authentication authorization

我坚持简单的事情:(

我有一个带有/ Admin / URL的ASP.NET MVC3应用程序。我把[Authorize]属性放在那里,就可以了。但现在我需要简单的事情:只用一个用户名/密码来限制对它的访问。

我不希望使用ASP.NET表单授权创建数据库,我需要它使用Visual Studio和IIS7服务器在我的开发PC上工作。

快速做到这一点的最佳方法是什么?我必须把它放到web.config中才能使它与“admin / p4ssw0rd”对配合使用?

2 个答案:

答案 0 :(得分:2)

请参阅:this question

您可以明确指定用户名和密码(如果您希望以纯文本格式使用密码,请注意解决方案。

答案 1 :(得分:1)

创建ASP.NET MVC 3应用程序时,Visual Studio添加了AccountController。只需修改LogOn操作,即可以手动执行验证,而不是查看数据库:

public class AccountController : Controller
{

    ...

    [HttpPost]
    public ActionResult LogOn(LogOnModel model, string returnUrl)
    {
        if (ModelState.IsValid)
        {
            // Here you can check the username and password against any data
            // store you want
            if (model.UserName == "admin" && model.Password == "p4ssw0rd")
            {
                FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                    && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                {
                    return Redirect(returnUrl);
                }
                else
                {
                    return RedirectToAction("Index", "Home");
                }
            }
            else
            {
                ModelState.AddModelError("", "The user name or password provided is incorrect.");
            }
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }

    ...

}
相关问题