Asp.net

HttpContext.Current.User != HttpContext.User?

  • May 22, 2013

全域 asax 中的HttpContext.Current.User與操作方法中的HttpContext.User不同嗎?我為使用者分配了一些角色,但他們似乎迷路了。

下面的程式碼顯示了正在發生的事情。當使用者登錄時,這兩個斷言都會被命中,首先是全域 asax,然後是 action 方法。然而,它們給出了不同的結果。

首先這個:

protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
   // ... omitted some code to check user is authenticated
   FormsIdentity identity = (FormsIdentity)HttpContext.Current.User.Identity;

   string[] roles = new string[] { "admin", "user" };

   HttpContext.Current.User =
       new System.Security.Principal.GenericPrincipal(identity, roles);

   Assert(HttpContext.User.IsInRole("admin"));
}

然後在我的操作方法中:

public ActionResult Index()
{
   bool isAdmin = HttpContext.User.IsInRole("admin");

   Assert(isAdmin); // this fails, isAdmin is false

   // ...
}

我使用了以下資源

這個答案

http://csharpdotnetfreak.blogspot.com/2009/02/formsauthentication-ticket-roles-aspnet.html

您的問題標籤上寫著“aspnet-mvc (3 and 4)”,那麼您是否可以選擇使用以下內容讓您的生活更輕鬆?如果您在 VS2012 中使用MVC 4 Internet 應用程序模板中的Simple Membership,這將為您開箱即用):

CreateUserAndAccount優點是也很容易為 UserProfile 設置屬性,例如:

WebSecurity.CreateUserAndAccount(newUser.UserName, newUser.Password,
   new { FullName = newUser.FullName, Email = newUser.Email, Timezone = newUser.TZ });
Roles.AddUserToRoles(newUser.UserName, new[] {"admin", "user"});

編輯,我意識到上面沒有回答你關於.User屬性等價的原始問題。

HttpContext在 Controller 中是一個屬性:Controller.HttpContext. HttpContextglobal.asax.cs 中是靜態類,所以這就是你使用HttpContext.Current. 他們指的是同一件事。

如果您執行以下程式碼,您可以看到它們顯然是“相同的主體”。所以問題是你分配的角色發生了什麼?

protected void Application_AuthenticateRequest(object sender, EventArgs e) {
   ...
   FormsIdentity identity = (FormsIdentity)HttpContext.Current.User.Identity;
   string[] roles = new string[] { "admin", "user" };
   identity.Label = "test label";
   System.Security.Principal.GenericPrincipal ppl = new System.Security.Principal.GenericPrincipal(identity, roles);            
   HttpContext.Current.User = ppl;
... }

public ActionResult Index() {
   bool isAdmin = HttpContext.User.IsInRole("admin");
   bool isAdmin2 = System.Web.HttpContext.Current.User.IsInRole("admin");
   System.Web.Security.FormsIdentity identity = (System.Web.Security.FormsIdentity)HttpContext.User.Identity;

   // The label is carried through from Application_AuthenticateRequest to Index.
   string label = identity.Label;
}

問題是,您分配了一個GenericPrincipalto .User。根據RoleProvider,這可以在RoleManagerModule期間被覆蓋(例如被 )PostAuthenticateRequest和(例如)變成RolePrincipal。然後,這可以推遲回數據庫(再次取決於提供者)來獲取角色,因此覆蓋您的角色。如果你在裡面工作,Application_OnPostAuthenticateRequest你可能會沒事的。

引用自:https://stackoverflow.com/questions/16693043