2014-05-21 42 views
0

我有一個憑證方法來通過GenericPrincipal設置用戶憑證。我使用asp.net MVCGenericPrincipal IsInRole爲HttpContext.User返回false

public void SetCredentials(HttpContextBase context, string username, bool createPersistenceCookie) 
    { 
     FormsAuthentication.SetAuthCookie(username, createPersistenceCookie); 

     IIdentity identity = new GenericIdentity(username); 
     IPrincipal principal = new GenericPrincipal(identity,new []{"standart"}); 

     context.User = principal; 
    } 

我要檢查User.IsInRole( 「非標準」)在控制器動作,但它返回false。

  • context.User.IsInRole( 「非標準」)

我想用context.User在我的應用程序,但它總是返回假//返回false。

+0

上下文用戶是否與CurrentPrincipal相同? – Prescott

+0

「Thread.CurrentPrincipal.IsInRole(」standart「)'返回true的事實與您帖子的標題矛盾。我建議你調查Thread.CurrentPrincipal和context.User是否和你的'principal'是同一個實例。 – chiccodoro

回答

1

我想你以前使用過asp.net會員api。現在你想在應用程序中創建自定義主體。

當你發送請求到服務器時,服務器使用一個新的乾淨的HttpContext。所以你失去了你的舊信息。如果你想使用舊的會話信息是應用程序,你可以將你的數據保存在服務器或客戶端。你可以這樣做兩種。

  • 客戶端的cookie
  • 服務器會話

我建議您使用客戶端的cookie。由於數據存儲在客戶端,因此您可以節省服務器資源。

public void SetCredentials(HttpContextBase context, string username, bool createPersistenceCookie) 
    { 
     var formsAuthenticationTicket = new FormsAuthenticationTicket(
      1, 
      username, 
      DateTime.Now, 
      DateTime.Now.AddMilliseconds(FormsAuthentication.Timeout.TotalMilliseconds), 
      createPersistenceCookie, 
      roles 
     ); 

     var encryptedTicket = FormsAuthentication.Encrypt(formsAuthenticationTicket); 
     var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket); 

     HttpContext.Current.Response.AppendCookie(authCookie); 
    } 

我將加密的cookie發送到客戶端。我應該檢查這個cookie所有傳入的請求到服務器應用程序。

現在在的Global.asax文件

protected void Application_AuthenticateRequest(object sender, System.EventArgs e) 
    { 
     HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName]; 

     if (authCookie == null) return; 

     FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value); 

     IIdentity identity = new GenericIdentity(ticket.Name); 
     IPrincipal principal = new GenericPrincipal(identity, ticket.UserData.Split('|')); 

     HttpContext.Current.User = principal; 
    } 

我希望解決您的問題。