如何在覆盖 Ocelot 和 .Net WebApi 中的 AuthorizationMiddleware 时 return 未经授权的响应

How to return Unauthorized response while overriding AuthorizationMiddleware in Ocelot & .Net WebApi

我正在尝试使用 .NET 5 WebApi 中的 OcelotPipelineConfiguration 覆盖 Ocelot AuthorizationMiddleware。这是我的代码:

已更新

配置

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IAuthorizationService authorizationService)
        {
            if (env.EnvironmentName == Environments.Development)
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseAuthentication();

            var configuration = new OcelotPipelineConfiguration
            {
                AuthorizationMiddleware = async (ctx, next) =>
                {

                    if (! await authorizationService.IsValid(ctx))
                    {
                        ctx.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                        await ctx.Response.WriteAsync("Some Error !");
                    }
                    else
                    {
                        await next.Invoke();
                    }
                },
            };
            app.UseOcelot(configuration).Wait();
        }

已更新

配置服务

        public void ConfigureServices(IServiceCollection services)
        {
            string AuthenticationKey = "AuthenticationKey";
            services.AddLogging();
            services.AddAuthentication(option =>
            {
                option.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                option.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(AuthenticationKey, option =>
             {
                 option.RequireHttpsMetadata = true;
                 option.SaveToken = true;
                 option.TokenValidationParameters = new TokenValidationParameters
                 {
                     IssuerSigningKey =
                         new SymmetricSecurityKey(
                             Encoding.ASCII.GetBytes(Configuration.GetSection("SecretKey").Value)),
                     ValidateIssuerSigningKey = true,
                     ValidateIssuer = false,
                     ValidateAudience = false
                 };

                 //option.ForwardSignIn

             });

            services.AddHttpClient<IAuthorizationService, AuthorizationService>();

            services.AddScoped<IJWTHelpers, JWTHelpers>();

            services
                .AddOcelot()
                .AddDelegatingHandler<HeaderDelegatingHandler>();

            services.AddMvc();
        }

如您所见,在某些情况下,我需要 return 立即响应,例如 Unauthorized,但我的代码总是 return a 500 Internal Server Error 给 Postman。 我搜索了很多,发现了 this 个问题。但是我在 HTTPContext 中找不到 Errors.Add 方法。 有什么想法可以 return 立即进行未经授权的响应吗?

我通过@Artur 评论找到了正确答案。 我替换了

    ctx.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
    await ctx.Response.WriteAsync("Some Error !");

Configure方法中用这个:

    ctx.Items.SetError(new UnauthorizedError("your custom message"));
    return;