SetAuthCookie
使用更新后的值更新包含 FormsAuth 票证的 cookie,但它不设置User
当前上下文的 cookie。您可以通过创建新的IPrincipal
and来更改当前上下文的用户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
isFormsIdentity
和 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 票证的更多信息。