2

일부 경로 (웹 사이트)로 들어오는 요청을 로그인 페이지로 리디렉션하지만 다른 경로 (API 경로)로 들어오는 요청에 대한 인증되지 않은 요청에 어떻게 대응합니까? AutomaticChallenge가 모든 웹 앱에 대해이 동작을 변경한다는 것을 이해합니다. 그러나 그것을 조건부로 만드는 방법은?ASP.NET Core에서 조건부 AutomaticChallenge를 구현하는 방법은 무엇입니까?

OpenId Connect 서버 구성 라이브러리 인 OpenIddict를 사용합니다. 그리고 일반적으로 클라이언트는 모바일 앱입니다. 그러나보기를 반환하는 일부 컨트롤러의 경우와 같은 웹 사이트가 있으면 좋을 것입니다.

시작 코드는이 방법을 찾습니다

// ... 
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 아니라고 생각 :

 // 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

당신이 MapWhen 또는 UseWhen 사용할 수 있습니다 AutomaticChallenge을 변경합니다. 요청이 ajax이면 CookieAuthentication 미들웨어는 401로 응답하고 그렇지 않으면 로그인 경로로 리디렉션합니다. 따라서 조건부 미들웨어를 사용할 필요가 없습니다.

+0

시작 질문에서 코드를 업데이트했습니다. – Andrii

+0

또한 자신의 Scenerio에 'AuthenticationScheme'을 사용할 수 있습니다. 하지만 그것은 나를 위해 광범위하고 많은 솔루션이있을 수 있기 때문에 나는 당신의 scenerio에 대한 답변을 쓸 수 없습니다. –