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

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

如何将来自某个路径(网站)的请求重定向到登录页面,但对来自另一个路径(API 路径)的请求进行未经授权的响应? 据我了解,AutomaticChallenge 改变了所有网络应用程序的这种行为。但如何使其成为有条件的呢?

我使用 OpenIddict,它是 OpenId Connect Server 配置库。 一般来说,客户端是移动应用程序。不过,对于某些返回 View 的 Controller 来说,如果有一个类似网站的行为那就太好了。

启动代码如下所示:

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

最佳答案

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

关于asp.net-core - 如何在 ASP.NET Core 中实现条件自动挑战?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38467872/

相关文章:

asp.net-mvc-4 - 将 ASP.NET Core 与旧版 .Net Framework 代码混合

razor - 在 Razor 页面中获取路由值

asp.net-core - 项目 'XXXXXX' 没有锁定文件。请运行 "dotnet restore"生成新的锁定文件

c# - 调用 Google GCM 时未经授权

asp.net-core - 修改 MVC 6 的原始 html 输出

.net - 基于策略的授权与在.Net Core中的角色进行授权

c# - 如何为标准框架和 .Net Core 创建 nuget 包(dll)?

c# - AuthorizationHandler 和数据库依赖注入(inject)

java - Spring-Security-Oauth2:访问此资源需要完全身份验证

iphone - 无法从 iPhone 应用程序获取 401 响应(未经授权)