2013-02-05 23 views
1

一旦用戶登錄到系統,我已在User.Identity.Name中保存認證信息。使用this方法mvc3更改認證值

FormsAuthentication.SetAuthCookie(Id + " | " + Name + " | " + Language + " | " + Culture + " | " + Email + " | " + Role+ " | " + TimeOffset+ " | " + Rights, RememberMe); 

現在我想改變裏面User.Identity.Name的一些值,當用戶改變一些configutation設置,如Language

但在調用FormsAuthentication.SetAuthCookie()之後,User.Identity.Name裏面的值不會再改變

string identity = HttpContext.Current.User.Identity.Name; // modify current value 
FormsAuthentication.SetAuthCookie(identity, false); // assign new value 

如何更改此值?

回答

1

SetAuthCookie更新包含具有更新值的FormsAuth票證的Cookie,但不會設置當前上下文的User。您可以通過創建新的IPrincipalIIdentity來更改當前上下文的用戶。這與獲取當前HttpContext並設置User屬性一樣簡單。

您通常會在IHttpModule或Global.asax.cs PostAuthenticateRequest事件中執行此操作,因爲此時FormsAuth已經對用戶的票證進行了身份驗證並設置了身份。在此事件發生後,您創建的新IPrincipal將在申請的其餘部分提供給申請人。

protected void Application_PostAuthenticateRequest(object sender, EventArgs args) 
{ 
    var application = (HttpApplication)sender; 
    var context = application.Context; 

    if (context.User != null || !context.User.Identity.IsAuthenticated) return; // user not authenticated, so you don't need to do anything else 

    // Here, you'd process the existing context.User.Identity.Name and split out the values you need. that part is up to you. in my example here, I'll just show you creating a new principal 
    var oldUserName = context.User.Identity.Name; 
    context.User = new GenericPrincipal(new GenericIdentity(oldUserName, "Forms"), new string[0]); 
} 

順便說一句,我不建議在標識名稱包裝的價值觀,而是票證的UserData財產。在這種情況下,你可以檢查context.User.IdentityFormsIdentity和訪問Ticket.UserData

protected void Application_PostAuthenticateRequest(object sender, EventArgs args) 
{ 
    var application = (HttpApplication)sender; 
    var context = application.Context; 

    if (context.User != null || !context.User.Identity.IsAuthenticated) return; // user not authenticated, so you don't need to do anything else 

    var formsIdentity = context.User.Identity as FormsIdentity; 

    if (formsIdentity == null) return; // not a forms identity, so we can't do any further processing 

    var ticket = formsIdentity.Ticket; 

    // now you can access ticket.UserData 
    // to add your own values to UserData, you'll have to create the ticket manually when you first log the user in 

    var values = ticket.UserData.Split('|'); 

    // etc. 
    // I'll pretend the second element values is a comma-delimited list of roles for the user, just to illustrate my point 
    var roles = values[1].Split(','); 


    context.User = new GenericPrincipal(new GenericIdentity(ticket.Name, "Forms"), roles); 
} 

Here是用的UserData自定義值創建FormsAuth門票一些更多的信息。