1

User.Identity.Name用户登录系统后,我已将身份验证信息存储在其中。使用这种方法

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

如何更改此值?

4

1 回答 1

1

SetAuthCookie使用更新后的值更新包含 FormsAuth 票证的 cookie,但它不设置User当前上下文的 cookie。您可以通过创建新的IPrincipaland来更改当前上下文的用户IIdentity。就像获取电流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.IdentityisFormsIdentity和 access是否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); 
}

以下是有关在 UserData 中使用自定义值创建 FormsAuth 票证的更多信息。

于 2013-02-05T06:31:19.343 回答