Search code examples
c#headerauthorizationasp.net-core-webapi.net-core-2.0

How to do simple header authorization in .net core 2.0?


I have been unable to find information on this particular issue after the 2.0 changes to .NET Core.

I have cookie authorization like this:

services.AddAuthentication("ExampleCookieAuthenticationScheme")
    .AddCookie("ExampleCookieAuthenticationScheme", options => {
         options.AccessDeniedPath = "/Account/Forbidden/";
             options.LoginPath = "/Account/Login/";
});

For another part (of my controllers I would like to simply authorize based on a simple header. In the examples I've found, either I am unable to get the headers, or they have been made only for facebook, google, cookies etc.

How do I add an authorization that performs a simple header check in .Net core 2.0?


Solution

  • It is possible to perform simple authorization check using a custom middleware. But if it is required to apply the custom middleware for selected controllers or action methods, you can use Middleware filter.

    Middleware and its app builder extension:

    public class SimpleHeaderAuthorizationMiddleware
        {
            private readonly RequestDelegate _next;
    
            public SimpleHeaderAuthorizationMiddleware(RequestDelegate next)
            {
                _next = next;
            }
    
            public async Task Invoke(HttpContext context){ 
    
                string authHeader = context.Request.Headers["Authorization"];
                if(!string.IsNullOrEmpty(authHeader))
                {
                    //TODO
                    //extract credentials from authHeader and do some sort or validation
                    bool isHeaderValid =  ValidateCredentials();
                    if(isHeaderValid){
                        await _next.Invoke(context);
                        return;
                    }
    
                }
    
                //Reject request if there is no authorization header or if it is not valid
                context.Response.StatusCode = 401; 
                await context.Response.WriteAsync("Unauthorized");
    
            }
    
        }
    
    public static class SimpleHeaderAuthorizationMiddlewareExtension
        {
            public static IApplicationBuilder UseSimpleHeaderAuthorization(this IApplicationBuilder app)
            {
                if (app == null)
                {
                    throw new ArgumentNullException(nameof(app));
                }
    
                return app.UseMiddleware<SimpleHeaderAuthorizationMiddleware>();
            }
        }
    

    In order to use middleware as a filter, you need to create a type with Configure method that specifies the middleware pipeline that you want to use.

    public class SimpleHeaderAuthorizationPipeline
        {
            public void Configure(IApplicationBuilder applicationBuilder){
                applicationBuilder.UseSimpleHeaderAuthorization();
            }
        }
    

    Now you can use the above type in specific controller or action methods like this:

    [MiddlewareFilter(typeof(SimpleHeaderAuthorizationPipeline))]
    public class ValuesController : Controller
    {
    }