SetAuthCookie
FormsAuthチケットを含む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チケットを作成する方法について詳しく説明します。