私はフォーム認証を使用しており、認証のためにサーバーにAajxリクエストを送信しています。 jsonの結果に基づいて、クライアントはどこに何をすべきかを決定します。これが、FormsAuthentication.RedirectFromLoginPageを使用してajax/json応答を妨害しない理由です。
この場合、Membership.ValidateUserでユーザーを検証した後でも、Request.IsAuthenticatedはfalseを返します。それから私はクッキーを設定します
FormsAuthentication.SetAuthCookie(username, false);
2番目のパラメーターである永続的なCookieはfalseですが、Cookieはブラウザーセッション全体で引き続き有効です。
FormsAuthentication.RedirectFromLoginPageを使用せずにRequest.IsAuthenticatedを機能させる方法はありますか?
要求の現在のセキュリティプリンシパルを更新する必要があります。 Response. Redirect(...)
を呼び出すと、新しい要求が行われ、セキュリティプリンシパルが再初期化され、この場合はRequest.IsAuthenticatedがtrueを返します。 _FormsAuthentication.RedirectFromLoginPage
_は内部でResponse. Redirect(...)
を呼び出します。次のように、現在のリクエストのセキュリティプリンシパルを手動で更新できます。
_public void RenewCurrentUser()
{
System.Web.HttpCookie authCookie =
System.Web.HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
FormsAuthenticationTicket authTicket = null;
authTicket = FormsAuthentication.Decrypt(authCookie.Value);
if (authTicket != null && !authTicket.Expired)
{
FormsAuthenticationTicket newAuthTicket = authTicket;
if (FormsAuthentication.SlidingExpiration)
{
newAuthTicket = FormsAuthentication.RenewTicketIfOld(authTicket);
}
string userData = newAuthTicket.UserData;
string[] roles = userData.Split(',');
System.Web.HttpContext.Current.User =
new System.Security.Principal.GenericPrincipal(new FormsIdentity(newAuthTicket), roles);
}
}
}
_
FormsAuthentication.SetAuthCookie
メソッド指定されたユーザー名の認証チケットを作成し、それを応答のCookieコレクションに、またはCookieなしの認証を使用している場合はURLに追加します。
参照: msdn
フォーム認証制御フロー をご覧ください。認証Cookieは応答Cookieコレクションに設定され、httpプロトコルレベルで監視できる必要があります(これを確認するには、FireCookieまたはFiddler2を使用します)。
メンバーシップはユーザー名/パスワードのみを検証します。 MembershipもSetAuthCookie()
も現在のリクエストを変更しません。彼らはCookieを呼び出し元に送り返すことを期待しており、nextリクエストはIsAuthenticated
のようなプロパティがtrueを返すときです。
カスタムIIdentity
およびIPrincipal
を使用してこれらのautomaticプロセスをオーバーライドおよび拡張し、認証イベントにフックできることに注意してください。もしあなたが必要ならば。
POSTの後のリダイレクトはベストプラクティスであり、正しい解決策と見なす必要があります。
場合によっては、ユーザーが認証要求のスコープ内で認証されているかどうかを確認する必要がある場合があります(たとえば、他の要求と共有される認証の実行後に追加のロジックを実行している場合)。
この場合、次のコードでRequest.IsAuthenticatedの値をリセットできます。
// set the forms auth cookie
FormsAuthentication.SetAuthCookie(username, createPersistentCookie);
// reset request.isauthenticated
var authCookie = System.Web.HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
if (authTicket != null && !authTicket.Expired)
{
var roles = authTicket.UserData.Split(',');
System.Web.HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(new FormsIdentity(authTicket), roles);
}
}
ここの投稿を参照してください: http://abadjimarinov.net/blog/2010/01/24/RenewUserInTheSameRequestInAspdotNET.xhtml
これを簡単に使用できます
FormsAuthentication.SetAuthCookie(username、true);