SetAuthCookieFormsAuthチケットを含むCookieを更新された値で更新しますがUser、現在のコンテキストのを設定しません。IPrincipal新しいとを作成することにより、現在のコンテキストのユーザーを変更できますIIdentity。電流を取得してプロパティHttpContextを設定するのと同じくらい簡単です。User
この時点でFormsAuthはすでにユーザーのチケットを認証し、IDを設定しているため、通常はIHttpModuleイベントのorGlobal.asax.csでこれを行います。PostAuthenticateRequestこのイベントの後、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]);
}
余談ですが、ID名ではなく、チケットの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);
}
UserDataでカスタム値を使用してFormsAuthチケットを作成する方法について詳しく説明します。