繁体   English   中英

HttpContext.User.Identity.IsAuthenticated永远不会是真的

[英]HttpContext.User.Identity.IsAuthenticated never true

登录

[HttpPost]
public ActionResult Login(LoginModel loginModel)
{
    if (ModelState.IsValid)
    {
        using (var _Db = new AccountContext())
        {
            var _UserAccount = _Db.UserAccounts.FirstOrDefault(u => u.Username == loginModel.Username && u.Password == loginModel.Password);

            if (_UserAccount == null)
            {
                ModelState.AddModelError("", "Account doesn't exist!");
            }
            else
            {
                FormsAuthentication.SetAuthCookie(loginModel.Username, false);
            }
        }
    }
    return RedirectToAction("Index", "Home");
}

重定向或显示视图

public ActionResult Index()
{
    if (HttpContext.User.Identity.IsAuthenticated)
    {
        return View("Index");
    }
    else
    {
        return RedirectToAction("LoginPage");
    }
}

我已经完成了代码,可以看到使用正确的用户名调用SetAuthCookie。 FormsAuthentication.SetAuthCookie(loginModel.Username, false);

什么可以阻止用户进行身份验证?

什么可以阻止用户进行身份验证?

一个可能的原因是您忘记在web.config中启用表单身份验证:

<system.web>
    <authentication mode="Forms">
      <forms loginUrl="~/Account/Login" timeout="2880" />
    </authentication>
    ...
</system.web>

您可能还想检查在调用SetAuthCookie方法后是否在浏览器中发出表单身份验证cookie。 默认情况下,此cookie将被称为.ASPXAUTH 如果存在此类cookie且票证尚未过期,则HttpContext.User.Identity.IsAuthenticated方法将返回true。

我遇到了同样的问题,即使将<authentication mode="Forms">标记添加到我的web.config文件后,问题仍然存在。 就像我在那里一样,我注意到:

<system.webServer> <modules> <remove name="FormsAuthentication" /> </modules> </system.webServer>

我引用了另一个MVC项目web.config文件并看到了一个区别

<system.webServer> <modules> <remove name="FormsAuthenticationModule" /> </modules> </system.webServer>

我将值更改为<remove name="FormsAuthenticationModule" /> ,瞧! - 它现在有效。 对不起,我不明白为什么,或者那里发生了什么,但我希望可以帮助别人。

您需要先验证用户:

WebSecurity.Login(loginModel.UserName, loginModel.Password);

只有在那之后才能设置auth cookie。

暂无
暂无

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

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