用户登录系统后,我已在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
如何更改此值?
答案 0 :(得分:1)
SetAuthCookie
使用更新后的值更新包含FormsAuth票证的cookie,但不会设置当前上下文的User
。您可以通过创建新的IPrincipal
和IIdentity
来更改当前上下文的用户。它就像获取当前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票证的更多信息。