0

Currently, I have applied RequiredAuthorization method on each endpoints as below

 endpoints.MapPost($"{ProductsConfigs.ProductsPrefixUri}", CreateProducts)
            .WithTags(ProductsConfigs.Tag)
            .RequireAuthorization()
            .Produces<CreateProductResult>(StatusCodes.Status201Created)
            .Produces(StatusCodes.Status401Unauthorized)
            .Produces(StatusCodes.Status400BadRequest)
            .WithName("CreateProduct")
            .WithDisplayName("Create a new product.");

and I have lot of endpoints ex:

endpoints.MapCreateProductsEndpoint()
            .MapDebitProductStockEndpoint()
            .MapReplenishProductStockEndpoint()
            .MapGetProductByIdEndpoint()
            .MapGetProductsViewEndpoint();

And I know, I want to apply RequiredAuthorization method for each endpoints. Would like to know is there way to apply RequirementAuthorization for all these endpoints in one place. I have other set of endpoints where I don't want to apply RequireAuthroization method as well just for your information.

Please suggest the right approach.

Tiny Wang
  • 10,423
  • 1
  • 11
  • 29
sameer
  • 1,635
  • 3
  • 23
  • 35

1 Answers1

0

You could try this middleware.
CustomMiddleware.cs

    public class CustomMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly string _policyName;

        public CustomMiddleware(RequestDelegate next)
        {
            _next = next;

        }

        public async Task Invoke(HttpContext httpContext)
        {
            if (httpContext.Request.Path=="the endpoint")
            {
                if (!httpContext.User.Identity.IsAuthenticated)
                {
                    await httpContext.ChallengeAsync();

                }
            }
            await _next(httpContext);
        }
    }

    // Extension method used to add the middleware to the HTTP request pipeline.  
    public static class CustomMiddlewareExtensions
    {
        public static IApplicationBuilder UseCustomMiddleware(this IApplicationBuilder builder)
        {
            
            return  builder.UseMiddleware<CustomMiddleware>(); 

            
        }
    }

program.cs

app.UseCustomMiddleware();
Qiang Fu
  • 1,401
  • 1
  • 2
  • 8