【问题标题】:User.Identity.IsAuthenticated is false even after successful form authentication and setauthcookie即使在成功的表单身份验证和 setauthcookie 之后,User.Identity.IsAuthenticated 也是 false
【发布时间】:2018-08-27 07:51:06
【问题描述】:

我有两个控制器 TokkenIssuer 和 Login。 我已将 [authorize] 用于 TokkenIssuer 中的方法 A,该方法采用登录控制器的视图,然后进入登录控制器的登录操作。

登录控制器:

public ActionResult Login(string user,string password,string returnUrl)
    {
        FormsAuthentication.SetAuthCookie(user, true);
        if (FormsAuthentication.Authenticate(user, password))
        {

            if (string.IsNullOrEmpty(returnUrl) && Request.UrlReferrer != null)
                returnUrl = Server.UrlEncode(Request.UrlReferrer.PathAndQuery);

            return RedirectToAction("B", "TokenIssuer");
        }
        return View();
    }

从登录我重定向到令牌发行者控制器中的动作 B。 我开始知道 User.Identity.IsAuthenticated 将在重定向到另一个控制器后变为真,但我无法获取用户对象,也无法在我的重定向控制器 (TokenIssuer) 中找到 User.Identity.IsAuthenticated 为真。

TokenIssuer 控制器

[Authorize]
    public ActionResult A()            //takes to Login view
    {
     return View();       
    }
    public ActionResult B()           //Redirected from Login controller
    {
       if(User.Identity.IsAuthenticated)                  // Getting False
        {
           string user = User.Identity.Name;
        }
    }

如何解决这个问题?

【问题讨论】:

    标签: asp.net-mvc razor asp.net-mvc-5 forms-authentication wif


    【解决方案1】:

    在下一个请求之前它将是错误的。

    这里有一个很好的解释:http://forums.asp.net/t/1177741.aspx

    简而言之,在 ASP.NET 管道中较早地设置了 User 对象,早在执行请求的 ASP.NET 页面代码之前。现在,在随后的访问中,ASP.NET 运行时将看到表单身份验证票证,并且 User.Identity.IsAuthenticated 将为 true,但在此请求中不会。

    参考:https://www.experts-exchange.com/questions/28063988/User-Identity-IsAuthenticated-is-false-after-a-successful-Login-Validation.html

    【讨论】:

      【解决方案2】:

      花了很多时间才找到问题。

      我知道,在 VS 2013 或更高版本中,当我们默认创建一个 Web 应用程序时,它会在 web.config 文件中添加以下代码,它会禁用基于表单/声明的身份验证来创建用户对象。

      <module>
          <remove name = "FormsAuthentication"/>
      </module>
      

      所以评论或删除。这对我有帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-09-22
        • 1970-01-01
        • 1970-01-01
        • 2014-02-17
        • 1970-01-01
        • 2018-03-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多