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門票一些更多的信息。