繁体   English   中英

如何在 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,它将用户/角色传递给 Global.asax 中的 Application_PostAuthenticateRequest
  5. 在该请求中,根据身份验证票证和角色创建了 GenericPrinciple
  6. HttpContext.Current.User 设置为上面的变量

现在我的问题是,既然我设置了使用该网站的当前用户是谁,我该如何引用它们? 后验证完成后,我检查当前用户,它为空。 我应该将原理设置为 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);
...
}

在 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?
   }
}

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

所以我只是简单地检查:

HttpContext.Current.User.Identity.IsAuthenticated

暂无
暂无

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

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