2

How do I redirect requests coming to some path (web site) to login page but respond with unauthorized to requests coming to another path (API paths)? As I understand AutomaticChallenge changes this behavior for all the web app. But how to make it conditional?

I use OpenIddict which is OpenId Connect Server configuration library. And, in general, clients are mobile apps. However it would be nice to have a web site like behavior for some controllers that return views.

Startup code looks this way:

        // 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();
Andrii
  • 1,081
  • 1
  • 11
  • 24

1 Answers1

2

To change AutomaticChallenge you can use MapWhen or UseWhen:

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

But I think your requirement is not about AutomaticChallenge. If request is ajax then CookieAuthentication middleware respond with 401 otherwise redirect to login path. So you don't need to conditional middleware.

adem caglin
  • 22,700
  • 10
  • 58
  • 78
  • You can also use `AuthenticationScheme` for your scenerio. But i can't write an answer for your scenerio because it is to broad for me and there may be many solution. – adem caglin Jul 20 '16 at 07:15