2013-02-05 43 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门票一些更多的信息。