2

如何将来自某个路径(网站)的请求重定向到登录页面,但以未经授权的方式响应来自另一个路径(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();
4

1 回答 1

2

要更改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 响应,否则重定向到登录路径。所以你不需要条件中间件。

于 2016-07-19T21:53:26.500 回答