它可以执行简单的授权使用自定义中间件进行检查。但是,如果需要为所选控制器或操作方法应用自定义中间件,则可以使用中间件过滤器。
中间件和应用生成扩展名:
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>();
}
}
为了使用中间件作为过滤器,你需要创建Configure
方法,指定要使用的中间件管道中的类型。
public class SimpleHeaderAuthorizationPipeline
{
public void Configure(IApplicationBuilder applicationBuilder){
applicationBuilder.UseSimpleHeaderAuthorization();
}
}
现在你可以使用在特定的控制器或动作方法的上述类型如下:
[MiddlewareFilter(typeof(SimpleHeaderAuthorizationPipeline))]
public class ValuesController : Controller
{
}