如何在Asp.Net Core MVC中实现自定义请求头校验以拦截不符合要求的请求?
Hey Stephan, let's tackle this problem step by step—restricting access to your ASP.NET Core MVC controllers to only requests with a custom Authorization header is totally doable, and I'll walk you through the most straightforward, maintainable ways to implement it.
Method 1: Custom Action Filter (Flexible for Controllers/Actions)
This approach is perfect if you want to apply the check to specific controllers, individual actions, or globally across all endpoints.
- Create a filter class that inherits from
ActionFilterAttribute, and override theOnActionExecutingmethod to validate the header:
using Microsoft.AspNetCore.Mvc.Filters; public class CustomAuthFilter : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext context) { // Check if the Authorization header exists if (!context.HttpContext.Request.Headers.TryGetValue("Authorization", out var authHeader)) { context.Result = new UnauthorizedResult(); return; } // Split the header into auth type and token (expected format: "CustomType YourToken") var authParts = authHeader.ToString().Split(' ', StringSplitOptions.RemoveEmptyEntries); if (authParts.Length != 2 || !authParts[0].Equals("YourCustomAuthType", StringComparison.OrdinalIgnoreCase)) { // Invalid auth type or malformed header context.Result = new UnauthorizedResult(); return; } // Validate the token (replace this with your actual token logic) var token = authParts[1]; if (!IsTokenValid(token)) { context.Result = new UnauthorizedResult(); return; } base.OnActionExecuting(context); } // Replace this with your real token validation (e.g., check against DB/cache/JWT) private bool IsTokenValid(string token) { return !string.IsNullOrEmpty(token) && token.StartsWith("Valid_AppToken_"); // Example condition } }
- Apply the filter:
- To a single controller or action:
[CustomAuthFilter] public class SecureController : Controller { public IActionResult Index() { return View(); } }
- Globally (all controllers/actions):
Add this to yourProgram.cswhen configuring services:
builder.Services.AddControllersWithViews(options => { options.Filters.Add<CustomAuthFilter>(); });
Method 2: Custom Middleware (Global Request Check)
If you want to validate the header for every incoming request (not just controller endpoints), middleware is the way to go.
- Create the middleware class:
public class CustomAuthMiddleware { private readonly RequestDelegate _next; public CustomAuthMiddleware(RequestDelegate next) { _next = next; } public async Task InvokeAsync(HttpContext context) { // Validate the Authorization header if (!context.Request.Headers.TryGetValue("Authorization", out var authHeader)) { context.Response.StatusCode = StatusCodes.Status401Unauthorized; await context.Response.WriteAsync("Missing required Authorization header"); return; } var authParts = authHeader.ToString().Split(' ', StringSplitOptions.RemoveEmptyEntries); if (authParts.Length != 2 || !authParts[0].Equals("YourCustomAuthType", StringComparison.OrdinalIgnoreCase)) { context.Response.StatusCode = StatusCodes.Status401Unauthorized; await context.Response.WriteAsync("Invalid Authorization type"); return; } var token = authParts[1]; if (!IsTokenValid(token)) { context.Response.StatusCode = StatusCodes.Status401Unauthorized; await context.Response.WriteAsync("Invalid or expired token"); return; } // If all checks pass, pass the request to the next middleware await _next(context); } private bool IsTokenValid(string token) { // Replace with your actual token validation logic return !string.IsNullOrEmpty(token) && token.Length > 15; // Example check } }
- Register the middleware in
Program.cs(order matters—place it afterUseRoutingand beforeUseAuthorization):
var app = builder.Build(); // ... other middleware (e.g., static files, error handling) app.UseRouting(); // Add your custom auth middleware here app.UseMiddleware<CustomAuthMiddleware>(); app.UseAuthorization(); app.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); app.Run();
Quick Tips
- Replace
YourCustomAuthTypewith your actual custom authorization scheme name (e.g.,MyAppAuth). - For token validation, you can integrate JWT, OAuth2, or your own internal token system—just swap out the
IsTokenValidmethod with your business logic. - If you need role/claim-based authorization later, you can combine these approaches with ASP.NET Core's built-in
IAuthorizationServicefor more granular control.
内容的提问来源于stack exchange,提问作者Stephan Pich
相关产品推荐
相关产品推荐

