繁体   English   中英

为什么我得到User.Identity.IsAuthenticated false

[英]Why do I get User.Identity.IsAuthenticated false

我得到的User.Identity.IsAuthenticated为false。 我认为这是造成我的第二个问题:我无法使用[Authorize]装饰器访问控制器。

我的代码去了:

  • 我的MembershipProvider继承,以及ValidateUser的实现:

     public override bool ValidateUser(string username, string password) { if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password)) return false; var user = DBManager.Context.Usuarios.First(x => x.Nombre == username); if (user.Pass != password) return false; return true; } 
  • 我的Web.Config身份验证部分:

     <authentication mode="Forms"> <forms loginUrl="~/Account/Login" defaultUrl="~/" timeout="20" slidingExpiration="true" /> </authentication> <membership defaultProvider="Membership"> <providers> <clear /> <add name="Membership" type="SGKS.Security.Membership" /> </providers> </membership> 
  • Contorller

     [HttpGet] [AllowAnonymous] public ActionResult Login() { if (User.Identity.IsAuthenticated) { return RedirectToAction("Index", "Facutra"); } return View(); } [HttpPost] [AllowAnonymous] public ActionResult Login(Login model) { if (ModelState.IsValid) { if (System.Web.Security.Membership.ValidateUser(model.Nombre, model.Pass)) { FormsAuthentication.SetAuthCookie(model.Nombre, model.Recordarme); } ViewBag.Error = "Usuario y/o contraseña incorrectos."; } return View(model); } 

我在这里找到了答案:

当您在成功进行身份验证时调用FormsAuthentication.SetAuthCookie时,您FormsAuthentication.SetAuthCookie身份验证cookie添加到响应中 该cookie将存储在客户端浏览器中,并在后续请求中发送。 因此,只有在后续请求下,该用户才被视为已认证。 因此,您需要在调用SetAuthCookie方法之后始终进行重定向。

换句话说,您需要在调用FormsAuthentication.SetAuthCookie之后立即添加RedirectToAction

[HttpPost]
[AllowAnonymous]
// The ASP.NET framework automatically puts a returnUrl query string parameter of the original
// page the user requested. You just need to add that parameter here to gain access to it
// (assuming you want to redirect the user back to the original requested page rather than 
// some start page).
public ActionResult Login(Login model, string returnUrl)
{
    if (ModelState.IsValid)
    {
        if (System.Web.Security.Membership.ValidateUser(model.Nombre, model.Pass))
        {
            FormsAuthentication.SetAuthCookie(model.Nombre, model.Recordarme);

            // Redirect so the next request can see the user as authenticated
            if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
            {
                return Redirect(returnUrl);
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
        }
        ViewBag.Error = "Usuario y/o contraseña incorrectos.";
    }
    return View(model);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM