2

Wie leite ich Anfragen, die auf einen Pfad (Website) kommen, auf die Anmeldeseite um, reagiere aber mit nicht autorisierten Anfragen auf einen anderen Pfad (API-Pfade)? Wie ich verstehe, ändert AutomaticChallenge dieses Verhalten für alle Web-App. Aber wie macht man das bedingt?So implementieren Sie bedingte AutomaticChallenge in ASP.NET Core?

Ich benutze OpenIddict, die OpenId Connect Server Konfigurationsbibliothek ist. Und im Allgemeinen sind Clients mobile Apps. Es wäre jedoch nett, für einige Controller, die Ansichten zurückgeben, ein webseitenähnliches Verhalten zu haben.

Startup-Code sieht so aus:

 // 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(); 

Antwort

1

AutomaticChallenge ändern können Sie MapWhen oder UseWhen verwenden:

// ... 
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, 
     }); 
     // ... 
}); 

Aber Ich denke, Ihre Anforderung nicht über AutomaticChallenge ist. Wenn die Anfrage Ajax ist, dann antworten Sie mit CookieAuthentication Middleware mit 401 andernfalls Redirect zu Login-Pfad. Sie brauchen also keine bedingte Middleware.

+0

Aktualisierte Frage mit einem Code von Startup – Andrii

+0

Sie können auch 'AuthenticationScheme' für Ihr Szenario verwenden. Aber ich kann keine Antwort für dein Szenario schreiben, weil es zu breit für mich ist und es viele Lösungen geben kann. –

Verwandte Themen