Web API 2 OWINベアラートークンのCookieの目的は何ですか?質問する

Web API 2 OWINベアラートークンのCookieの目的は何ですか?質問する

MVC 5 のシングル ページ アプリ テンプレートの新しい OWIN Bearer Token 認証プロセスを理解しようとしています。間違っていたら訂正してください。OAuth パスワード クライアント認証フローの場合、Bearer Token 認証は、Bearer アクセス トークン コードの http 認証要求ヘッダーをチェックして、要求が認証されているかどうかを確認することで機能します。特定の要求が認証されているかどうかを確認するために Cookie に依存しません。

この投稿によると:

Web API サンプルを使用した OWIN ベアラー トークン認証

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
    using (IdentityManager identityManager = _identityManagerFactory.CreateStoreManager())
    {
        if (!await identityManager.Passwords.CheckPasswordAsync(context.UserName, context.Password))
        {
            context.SetError("invalid_grant", "The user name or password is incorrect.");
            return;
        }

        string userId = await identityManager.Logins.GetUserIdForLocalLoginAsync(context.UserName);
        IEnumerable<Claim> claims = await GetClaimsAsync(identityManager, userId);
        ClaimsIdentity oAuthIdentity = CreateIdentity(identityManager, claims,
            context.Options.AuthenticationType);
        ClaimsIdentity cookiesIdentity = CreateIdentity(identityManager, claims,
            _cookieOptions.AuthenticationType);
        AuthenticationProperties properties = await CreatePropertiesAsync(identityManager, userId);
        AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
        context.Validated(ticket);
        context.Request.Context.Authentication.SignIn(cookiesIdentity);
    }
}

GrantReourceOwnerCredentials 関数は、次の行でチケットを作成するだけでなく: context.Validated(ticket);、次の行で Cookie ID を作成し、それを Cookie に設定します: context.Request.Context.Authentication.SignIn(cookiesIdentity);

私の質問は、この関数の Cookie の正確な目的は何ですか? 認証目的には AuthenticationTicket で十分ではないでしょうか?

ベストアンサー1

SPA テンプレートでは、実際には Cookie 認証とトークン認証という 2 つの個別の認証メカニズムが有効になっています。これにより、MVC と Web API コントローラー アクションの両方の認証が可能になりますが、追加の設定が必要です。

WebApiConfig.Register メソッドを見ると、次のコード行が見つかります。

    config.SuppressDefaultHostAuthentication();

これはWeb APIにクッキー認証を無視するように指示し、以下で説明する多くの問題を回避します。質問で投稿したリンク:

「...SPA テンプレートは、MVC 認証などの他のシナリオを有効にするために、アプリケーション クッキー ミドルウェアをアクティブ モードとしても有効にします。したがって、リクエストにセッション クッキーがあってもベアラー トークンがない場合でも、Web API は認証されます。これはおそらく望ましくないことです。API が CSRF 攻撃を受ける可能性があるためです。もう 1 つの悪影響は、リクエストが承認されていない場合、両方のミドルウェア コンポーネントがチャレンジを適用することです。クッキー ミドルウェアは、401 応答を 302 に変更して、ログイン ページにリダイレクトします。これも、Web API リクエストでは望ましくないことです。」

そのため、認証を必要とする Web API 呼び出しでは、config.SuppressDefaultHostAuthentication()リクエストとともに自動的に送信される Cookie が無視され、「Bearer」で始まる Authorization ヘッダーが検索されます。MVC コントローラーは Cookie 認証を引き続き使用し、トークン認証メカニズムは Web ページ認証にはあまり適していないため、トークン認証メカニズムを認識しません。

おすすめ記事