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

无人久伴 提交于 2019-12-05 09:15:25

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
{
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!