Search code examples
asp.net-coreauthenticationasp.net-web-apiidentityserver4asp.net-authorization

Set request's header on Authorize Attribute of the Controller in Asp.net Core Web API


I want to set the header request before checking the auhorization, but i'm looking for the event to execute the modification. This my Implementation of IAuthorizationFilter :

public class MyAuthorizationFilter : IAuthorizationFilter
    {  

        public MyAuthorizationFilter()
        {
        }

        public void OnAuthorization(AuthorizationFilterContext context)
        {
        }
    }

This is my code in Startup :

services.AddMvc(options =>
            {
                options.Filters.Add(typeof(ClaimRequirementFilter));
            });

This is my call of MyAuthorizationFilter in the controller :

 [MyAuthorizationFilter()]
    public class AccountController : BaseController
    {
    }

Solution

  • To modify the request, add a middleware before the auth middleware:

    app.UseRouting();
    
    // add a middleware before auth
    app.Use(
        async (context, next) => {
            // modify the request
            context.Request.Headers["A"] = "1";
            // call the next middleware
            await next();
        }
    );
    
    app.UseAuthentication();
    app.UseAuthorization();
    
    app.UseEndpoints(...);