mvc3更改身份验证值

时间:2013-02-05 06:11:04

标签: c# asp.net-mvc asp.net-mvc-3

用户登录系统后,我已在User.Identity.Name内存储了身份验证信息。使用this方法

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

现在我想在用户更改某些配置设置时更改User.Identity.Name内的某个值,例如Language

但在致电FormsAuthentication.SetAuthCookie()后,User.Identity.Name内的值不再发生变化

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

如何更改此值?

1 个答案:

答案 0 :(得分:1)

SetAuthCookie使用更新后的值更新包含FormsAuth票证的cookie,但不会设置当前上下文的User。您可以通过创建新的IPrincipalIIdentity来更改当前上下文的用户。它就像获取当前HttpContext并设置User属性一样简单。

您通常在IHttpModule事件中的PostAuthenticateRequest或Global.asax.cs中执行此操作,因为此时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.Identity是否为FormsIdentity并访问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票证的更多信息。