我如何在 MVC 中引用 Application_PostAuthenticateRequest 之后的 HttpContext.Current.User?

How do I reference the HttpContext.Current.User after the Application_PostAuthenticateRequest in MVC?

下面是我的问题的分解步骤:

  1. 用户使用 Google 登录。
  2. 在登录回调中,收集有关用户的信息
  3. 根据用户分配角色
  4. 创建了一个 FormsAuthenticationTicket,它将 user/roles 传递给 Global.asax
  5. 中的 Application_PostAuthenticateRequest
  6. 在该请求中,根据身份验证票证和角色创建了一个 GenericPrinciple
  7. HttpContext.Current.User设置为上面的变量

现在我的问题是,既然我设置了当前使用该网站的用户是谁,我该如何引用他们? post 身份验证完成后,我检查当前用户,它为空。我应该将原则设置为 HttpContext.Current.User 以外的其他变量吗?

回调

public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
{
...
// Get roles for current user
string roles = "bob,adminbob,cthulu";

FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
   1,
   loginInfo.Email,
   DateTime.Now,
   DateTime.Now.AddMinutes(30), // value of time out property
   false,
   roles,
   FormsAuthentication.FormsCookiePath);

HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket));
Response.Cookies.Add(authCookie);
...
}

Post 在 Global.asax

中验证
protected void Application_PostAuthenticateRequest(Object sender, EventArgs e) {
    HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];

   if (authCookie != null) {
      FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
      string[] userRoles = authTicket.UserData.Split(new Char[] { ',' });
      GenericPrincipal userPrincipal = new GenericPrincipal(new GenericIdentity(authTicket.Name), userRoles);
      HttpContext.Current.User = userPrincipal; //How do I reference this in the program?
   }
}

没关系,我知道为什么返回空白了。当我调用检查名称的方法时,身份尚未通过身份验证。如果您尝试在未经身份验证的情况下获取名称,它将 returns 空白。

所以我只是简单地检查了一下:

HttpContext.Current.User.Identity.IsAuthenticated