How to apply RequireAuthorization Attribute for list of endpoints in minimal API

333 Views Asked by At

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.

1

There are 1 best solutions below

0
On

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