在web.config中进行表单身份验证

Jyo*_*asa 18 authentication asp.net-mvc

我正在使用MVC3并将用户身份验证放在web.config文件中.这是绕过sqlserver身份验证.

web.config中的代码如下:

<authentication mode="Forms">
      <forms loginUrl="~/Account/LogOn" timeout="2880" >
        <credentials passwordFormat="Clear">
          <user name="test123" password="test123" />
        </credentials>
      </forms>
</authentication>
Run Code Online (Sandbox Code Playgroud)

我尝试使用提到的用户ID和密码登录,我在页面中收到错误

登录失败.请更正错误,然后重试.

* The user name or password provided is incorrect.
Run Code Online (Sandbox Code Playgroud)

当我调试到AccountController.cs文件时,失败的MembershipService.ValidateUser(model.UserName, model.Password)方法.

Ale*_*yev 30

如果您检查标准的ASP.NET MVC 3 AccountController.csAccountModels.cs文件,您将了解内部使用的MembershipProvider.ValidateUser方法(通过Membership.Provider).如果要在web.config中存储密码,则应使用FormsAuthentication.Authenticate方法.

例如:

public class AuthorizationController : Controller
{
    public ActionResult LogOn()
    {
        return View("LogOn");
    }

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult LogOn(string userName, string password, 
        bool rememberMe, string returnUrl)
    {
        if (!ValidateLogOn(userName, password))
            return View("LogOn");

        FormsAuthentication.SetAuthCookie(userName, rememberMe);

        if (!string.IsNullOrEmpty(returnUrl))
            return Redirect(returnUrl);
        else
            return RedirectToAction("Index", "News");

    }

    private bool ValidateLogOn(string userName, string password)
    {
        if (string.IsNullOrEmpty(userName))
            ModelState.AddModelError("username", "User name required");

        if (string.IsNullOrEmpty(password))
            ModelState.AddModelError("password", "Password required");

        if (ModelState.IsValid && !FormsAuthentication.
            Authenticate(userName, password))
            ModelState.AddModelError("_FORM", "Wrong user name or password");

        return ModelState.IsValid;
    }

    public RedirectToRouteResult LogOff()
    {
        FormsAuthentication.SignOut();

        return RedirectToAction("LogOn");
    }
}
Run Code Online (Sandbox Code Playgroud)