SetAuthCookie
更新包含具有更新值的FormsAuth票证的Cookie,但不会设置当前上下文的User
。您可以通过创建新的IPrincipal
和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.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门票一些更多的信息。