19

我遇到了 MVC4 用户授权问题。

System.Web.Security.Membership.ValidateUser返回true
然后它开始了FormsAuthentication.SetAuthCookie,我在浏览器中看到了一个 cookie。
然后由于某种原因User.Identity.IsAuthenticated仍然评估为。重定向后仍然为假并保持。false
User.Identity.IsAuthenticatedfalse

[AllowAnonymous]
[HttpPost]
public ActionResult Login(LoginModel model, string returnUrl)
{
    if (ModelState.IsValid)
    {
        if (System.Web.Security.Membership.ValidateUser(model.UserName, model.Password))
        {
            FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
            if (Url.IsLocalUrl(returnUrl))
            {
                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);
}
4

3 回答 3

21

检查您的 webconfig,您必须启用表单身份验证:

在里面添加以下代码段

   <authentication mode="Forms">
      <forms loginUrl="~/Account/Login" timeout="3600" />
    </authentication>

如果它在您的 webconfig 中,请注释掉:

<!--<modules>
      <remove name="FormsAuthentication" />
</modules>-->

现在你可以检查

WebSecurity.CurrentUserName、WebSecurity.CurrentUserId 和、WebSecurity.IsAuthenticated 标志;

于 2015-05-02T02:34:27.870 回答
20

User.Identity.IsAuthenticated在调用FormsAuthentication.SetAuthCookie().

请参阅http://msdn.microsoft.com/en-us/library/twk5762b.aspx

SetAuthCookie 方法将表单身份验证票添加到 cookie 集合,如果 CookiesSupported 为 false,则添加到 URL。forms-authentication ticket 为浏览器发出的下一个请求提供表单认证信息。

于 2013-01-24T18:49:11.463 回答
1

它需要额外的往返(RedirectToAction),但这完成了我想要的。此外,我在此示例中没有使用强类型模型,但它演示了这个想法。代码检查用户是否经过身份验证,如果没有设置 cookie,则重定向到自身。第二次调用 IsAuthenticated 为 true 并返回 View。只需确保您的表单输入命名为用户名和密码。

[AllowAnonymous]
[HttpPost]
public ActionResult Login(string userName, string password, string returnUrl)
{
if (ModelState.IsValid)
{
    if (HttpContext.User.Identity.IsAuthenticated)
    {
        return View(returnUrl);
    }
    else
    {
        if (System.Web.Security.Membership.ValidateUser(userName, password))
        {
            FormsAuthentication.SetAuthCookie(userName, false);
            if (Url.IsLocalUrl(returnUrl))
            {
                return RedirectToAction("Login", new { userName = userName, password = password, returnUrl = returnUrl });
                //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);
}
于 2013-08-27T15:39:54.147 回答