如何在ASP.NET Core中实现条件自动挑战?

时间:2016-07-19 20:25:41

标签: asp.net-core asp.net-core-1.0 unauthorized challenge-response asp.net-core-middleware

如何将进入某个路径(网站)的请求重定向到登录页面,但未经授权响应来到另一个路径(API路径)的请求? 据我所知,AutomaticChallenge改变了所有Web应用程序的这种行为。但是如何让它有条件?

我使用OpenIddict这是OpenId Connect Server配置库。 而且,通常,客户端是移动应用程序。然而,对于一些返回视图的控制器来说,拥有一个类似行为的网站会很不错。

启动代码看起来像这样:

        // 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 个答案:

答案 0 :(得分: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响应,否则重定向到登录路径。所以你不需要有条件的中间件。