Wrong authentication in asp mvc 4

时间:2016-03-30 09:26:56

标签: c# asp.net .net asp.net-mvc asp.net-mvc-4

I have login page and I want to redirect to same page if the password or user name are invalid. This is the code in login post:

[HttpPost]
public ActionResult Login(LoginModel lm, string returnUrl)
{
    using (WorkLayer dal = new WorkLayer())
    {
        if (ModelState.IsValid)
        {
           // UserManager UM = new UserManager();
           //   string password = UM.GetUserPassword(ULV.LoginName);
            string password = dal.Users.GetUserInfo(lm.UserName).HashPassword.ToString();

            if (string.IsNullOrEmpty(password))
                ModelState.AddModelError("", "The user login or password provided is incorrect.");

            else
            {

                if (lm.HashPassword.Equals(password))
                {
                    FormsAuthentication.SetAuthCookie(lm.UserName, false);
                    return RedirectToAction("AdminPanel");
                } 
                else
                {
                    ModelState.AddModelError("", "The password provided is incorrect.");
                    return RedirectToAction("Login");
                }
            }
        } 
    }
    return View(lm);

}

And the code in Action Admin:

[Authorize]
public ActionResult AdminPanel()
{
    return View();
}

But every time when I enter correctly my username and password I receive:

HTTP Error 401.0 - Unauthorized You do not have permission to view this directory or page. Most likely causes:

The authenticated user does not have access to a resource needed to process the request.

1 个答案:

答案 0 :(得分:0)

您的[AllowAnonymous]操作似乎缺少Login属性。 AccountController通常具有[Authorize]属性,这意味着您需要允许匿名处理您希望尚未经过身份验证的请求。

[HttpPost]
[AllowAnonymous]
public ActionResult Login(LoginModel lm, string returnUrl) {...}

正如@StephenMuecke在评论中所提到的,您不需要重定向错误/无效凭据。让这个动作完成。

以下是重构的Login操作

[HttpPost]
[AllowAnonymous]
public ActionResult Login(LoginModel lm, string returnUrl) {
    using (WorkLayer dal = new WorkLayer()) {
        if (ModelState.IsValid) {
            string password = dal.Users.GetUserInfo(lm.UserName).HashPassword.ToString();

            if (!string.IsNullOrEmpty(password) && lm.HashPassword.Equals(password)) {
                FormsAuthentication.SetAuthCookie(lm.UserName, false);
                return RedirectToAction("AdminPanel");
            } else {
                ModelState.AddModelError("", "The user login or password provided is incorrect.");                    
            }
        } 
    }
    return View(lm);
}