Search code examples
asp.net-core-webapi.net-5api-gatewayasp.net-authorizationocelot

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


I'm tring to override Ocelot AuthorizationMiddleware using a OcelotPipelineConfiguration in .NET 5 WebApi. This is my code:

UPDATED

Configure

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

UPDATED

ConfigureServices

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

As you can see, in some situations I need to return an immediate response like Unauthorized, but my code always return a 500 Internal Server Error to Postman. I searched a lot and found this question. But I cann't find Errors.Add method in HTTPContext. Is there any Idea to return immediate Unauthorized response?


Solution

  • I found the correct answer by @Artur comment. I replaced

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

    in Configure Method with this one:

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