Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 436
Nixxon Avatar asked Oct 14 '17 12:10

Nixxon


People also ask

How do you pass basic authentication in header .NET core?

Basic authentication works as follows: If a request requires authentication, the server returns 401 (Unauthorized). The response includes a WWW-Authenticate header, indicating the server supports Basic authentication. The client sends another request, with the client credentials in the Authorization header.

How do I authorize a header?

The HTTP Authorization request header can be used to provide credentials that authenticate a user agent with a server, allowing access to a protected resource. The Authorization header is usually, but not always, sent after the user agent first attempts to request a protected resource without credentials.


1 Answers

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
{
}
like image 168
Yared Avatar answered Oct 05 '22 15:10

Yared