2

いくつかのパス(Webサイト)からログインページへのリクエストをリダイレクトする方法はありますが、別のパス(APIパス)へのリクエストに対する許可されていないリクエストで応答しますか? 私はAutomaticChallengeがすべてのWebアプリケーションのこの動作を変更することを理解しています。しかし、それを条件付きにする方法は?ASP.NETコアで条件付き自動チャレンジを実装する方法は?

私はOpenId Connectサーバー構成ライブラリであるOpenIddictを使用しています。 一般に、クライアントはモバイルアプリです。しかし、いくつかのコントローラがビューを返すような振る舞いのようなWebサイトを持っていると良いでしょう。

スタートアップコードはこのようになります:

 // Add a middleware used to validate access 
     // tokens and protect the API endpoints. 
     app.UseOAuthValidation(); 

     app.UseCsp(options => options.DefaultSources(directive => directive.Self()) 
      .ImageSources(directive => directive.Self() 
       .CustomSources("*")) 
      .ScriptSources(directive => directive.Self() 
       .UnsafeInline()) 
      .StyleSources(directive => directive.Self() 
       .UnsafeInline())); 

     app.UseXContentTypeOptions(); 

     app.UseXfo(options => options.Deny()); 

     app.UseXXssProtection(options => options.EnabledWithBlockMode()); 

     app.UseIdentity(); 

     // Add external authentication middleware below. To configure them please see http://go.microsoft.com/fwlink/?LinkID=532715 
     app.UseTwitterAuthentication(...); 

     app.UseFacebookAuthentication(...); 

     app.UseGoogleAuthentication(...); 

     app.UseSession(); 

     app.UseOpenIddict(); 

     app.UseMvc(routes => 
     { 
      routes.MapRoute(
       name: "default", 
       template: "{controller=Home}/{action=Index}/{id?}"); 
     }); 

     app.UseSwagger(); 
     app.UseSwaggerUi(); 

答えて

1

AutomaticChallengeを変更するには、MapWhenUseWhenを使用することができます。

// ... 
app.MapWhen(ctx => ctx.Request.Path.Value.StartsWith("/api"), builder => 
{ 
     builder.UseCookieAuthentication(new CookieAuthenticationOptions() 
     { 
      AutomaticChallenge = false, 
     }); 
     // ... 
}); 
app.MapWhen(ctx => !ctx.Request.Path.Value.StartsWith("/api"), builder => 
{ 
     builder.UseCookieAuthentication(new CookieAuthenticationOptions() 
     { 
      AutomaticChallenge = true, 
     }); 
     // ... 
}); 

しかし、私はあなたの条件を約AutomaticChallengeではないと思います。リクエストがajaxの場合、CookieAuthenticationミドルウェアは401で応答し、それ以外の場合はログインパスにリダイレクトします。したがって、条件付きミドルウェアは必要ありません。

+0

スタートアップからのコードで質問を更新 – Andrii

+0

また、あなたのscenerioに 'AuthenticationScheme'を使うこともできます。しかし私はあなたの風景の答えを書くことができません。なぜなら、それは私にとって広範であり、多くの解決策があるからです。 –

関連する問題