如何在.net core 2.0中进行简单的头文件授权?

Nix*_*xon 5 authorization header asp.net-core-webapi .net-core-2.0

在对.NET Core进行2.0更改后,我无法找到有关此特定问题的信息.

我有这样的cookie授权:

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

对于另一部分(我的控制器,我想简单地基于一个简单的标题进行授权.在我发现的例子中,要么我无法获得标题,要么它们仅用于facebook,google,cookies等.

如何在.Net core 2.0中添加执行简单标头检查的授权?

Yar*_*red 8

可以使用自定义中间件执行简单的授权检查.但是,如果需要为选定的控制器或操作方法应用自定义中间件,则可以使用中间件过滤器.

中间件及其应用程序构建器扩展:

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>();
        }
    }
Run Code Online (Sandbox Code Playgroud)

为了将中间件用作过滤器,您需要创建一个带有Configure方法的类型,该方法指定要使用的中间件管道.

public class SimpleHeaderAuthorizationPipeline
    {
        public void Configure(IApplicationBuilder applicationBuilder){
            applicationBuilder.UseSimpleHeaderAuthorization();
        }
    }
Run Code Online (Sandbox Code Playgroud)

现在您可以在特定的控制器或动作方法中使用上述类型,如下所示:

[MiddlewareFilter(typeof(SimpleHeaderAuthorizationPipeline))]
public class ValuesController : Controller
{
}
Run Code Online (Sandbox Code Playgroud)