1

User.Identity.Nameユーザーがシステムにログインしたら、認証情報を内部に保存しました。この方法を使用して

FormsAuthentication.SetAuthCookie(Id + " | " + Name + " | " + Language + " | " + Culture + " | " + Email + " | " + Role+ " | " + TimeOffset+ " | " + Rights, RememberMe);

User.Identity.Nameここで、ユーザーが構成設定を変更したときに、内部の値を変更したいと考えています。Language

しかし、 を呼び出した後FormsAuthentication.SetAuthCookie()、 内の値はUser.Identity.Nameもう変更されません

string identity = HttpContext.Current.User.Identity.Name; // modify current value
FormsAuthentication.SetAuthCookie(identity, false); // assign new value

この値を変更するにはどうすればよいですか?

4

1 に答える 1

1

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.IdentityFormsIdentityアクセスすることができます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チケットを作成する方法について詳しく説明します。

于 2013-02-05T06:31:19.343 に答える