设置cookie并验证后,User.Identity.IsAuthenticated返回false

cor*_*est 19 asp.net-mvc asp.net-mvc-4

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

System.Web.Security.Membership.ValidateUser回报true.
然后它到达FormsAuthentication.SetAuthCookie,我在浏览器中看到一个cookie.
然后由于某种原因User.Identity.IsAuthenticated仍然评估false.
User.Identity.IsAuthenticated重定向后仍然是假的并停留false.

[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);
}
Run Code Online (Sandbox Code Playgroud)

jru*_*ell 19

User.Identity.IsAuthenticated在调用后的下一个请求之前,不会设置为true FormsAuthentication.SetAuthCookie().

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

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

  • 重定向用户后,User.Identity.IsAuthenticated仍为false,并且保持为false. (3认同)

Nal*_*ran 19

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

在里面添加以下代码段

   <authentication mode="Forms">
      <forms loginUrl="~/Account/Login" timeout="3600" />
    </authentication>
Run Code Online (Sandbox Code Playgroud)

注释掉它是否在你的webconfig中:

<!--<modules>
      <remove name="FormsAuthentication" />
</modules>-->
Run Code Online (Sandbox Code Playgroud)

现在你可以检查一下

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

  • 你救了我@Nalan M. (2认同)