asp.net Core,用于自定义请求头的逻辑



我想创建一个Asp。. Net Core MVC,可以拒绝缺乏特定标头的请求。

例如:

我想访问一个控制器,并且只允许其头包含特定(自定义)授权类型和令牌的请求。

我做了一些研究,但我找不到任何关于这个话题的东西,给我一个想法,甚至如何开始。

您可以自定义一个中间件来检查请求头类型和值:

public class SimpleHeaderAuthorizationMiddleware
{
private readonly RequestDelegate _next;
public SimpleHeaderAuthorizationMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
string authHeader = context.Request.Headers["Accept"];
if (!string.IsNullOrEmpty(authHeader))
{
if (authHeader == "specific_value")
{
//do your stuff....
//throw new Exception("The HTTP header value is not correct!");
context.Response.StatusCode = 403;
}
await _next(context);
}
else
{
//reject the request if do not provide Authorization header
//throw new Exception("Necessary HTTP header not present!");
context.Response.StatusCode = 401;
}
}
}

创建中间件扩展方法

public static class SimpleHeaderAuthorizationMiddlewareExtension
{
public static IApplicationBuilder UseSimpleHeaderAuthorization(this IApplicationBuilder app)
{
if (app == null)
{
throw new ArgumentNullException(nameof(app));
}
return app.UseMiddleware<SimpleHeaderAuthorizationMiddleware>();
}
}

下面的代码从Startup.Configure调用中间件:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{        
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseSimpleHeaderAuthorization();  //add this...
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}

最新更新