formsauthenticationは.NET 3.5のPostBackの後、ユーザーDataフィールドを保存していません

StackOverflow https://stackoverflow.com/questions/3669204

質問

私は作成しました FormsAuthenticationTicket ゼロからですが、後でそれを取得するとき、 UserData 戻ってきていません。これが使用されているコードです:

FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                        1,
                        user.UserId,
                        DateTime.Now,
                        DateTime.MaxValue,
                        false,
                        user.UserType);

HttpCookie cookie = new HttpCookie(
     FormsAuthentication.FormsCookieName, 
     FormsAuthentication.Encrypt(ticket));

Response.Cookies.Add(cookie);

ただし、これを次のものに読んだとき Request, 、私はそれを見つけました UserData フィールドが空になりました:

string encryptedCookie = Request.Cookies[ FormsAuthentication.FormsCookieName ].Value;
FormsAuthenticationticket ticket = FormsAuthentication.Decrypt(encryptedCookie);
Assert.IsTrue( ticket.UserData.Length == 0 ); //TRUE!

何か案は?

役に立ちましたか?

解決

私は問題を見つけたと思います。独自のクッキー名を作成しても大丈夫だと思われます!から次のように変更してください:

HttpCookie cookie = new HttpCookie(
     FormsAuthentication.FormsCookieName, 
     FormsAuthentication.Encrypt(ticket));

HttpCookie cookie = new HttpCookie(
     "SiteCookie", 
     FormsAuthentication.Encrypt(ticket));

そして、質問に従ってそれを取得します:

string encryptedCookie = Request.Cookies[ "SiteCookie" ].Value;
FormsAuthenticationticket ticket = FormsAuthentication.Decrypt(encryptedCookie);
Assert.IsFalse( ticket.UserData.Length == 0 ); //Hooray! It works

その可能性のある.NETは、それをいくつかのトリッキーなことを行うので、新しいものにすることで正常に機能します。

アップデート:

また、ユーザーがウェブサイトを使用している間にチケットが期限切れになるため、チケットを更新する必要があります。

FormsAuthentication.RenewTicketIfOld(ticket); // Do before saving cookie

他のヒント

これは私にとってはうまくいきます:

//Create Form Authentication ticket
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, currentUser.userid.ToString(), DateTime.Now, DateTime.Now.AddMinutes(60), false, currentUser.ToString(), FormsAuthentication.FormsCookiePath);

string hashCookies = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashCookies);
cookie.HttpOnly = true;
HttpContext.Current.Response.Cookies.Add(cookie);

また、この問題に遭遇しました。しかし、本当の理由は、サーバーが同じCookieを2回設定し、2番目のCookieがユーザーDataフィールドを含む最初のCookieをオーバーライドすることだと思います。

Fiddlerによるクッキーライティングプロセスをキャプチャできます。この問題を示すスクリーンショットを次に示します。enter image description here

それで、これはどのように起こったのですか?私の状況では、ログインコントロールを使用して認証します。 Login ControlのAuthenticateイベントでは、ユーザー名とパスワードのManaullyを確認した後、CookieをユーザーDataで設定します。次に、設定します AuthenticateEventArgs.Authenticated=true, 、この時点で、デバッグウィンドウで、新しいCookieがformsauthentication.formscookienameにも等しい応答にキューに巻き込まれていることがわかります!私のソリューションは、AuthenticateEventargs.Authenticated = trueを設定する代わりに、デフォルトページにリダイレクトされます。

したがって、コードをデバッグして、認証Cookieが応答に2回キューになっているかどうかを確認できます。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top