[英]How can I validate Request.Headers["Authorization"] for all controller at a single place?
[HttpGet]
public IActionResult Get()
{
string token = Request.Headers["Authorization"];
// Validate token.
}
[HttpPost]
public IActionResult Post(int id)
{
string token = Request.Headers["Authorization"];
// Validate token.
}
如何在一个地方验证所有控制器的 Request.Headers["Authorization"] ?
您可以创建和使用自定义中间件,您可以在其中检查标头并验证是否应将其传递给控制器。
要实现创建中间件类并在 Startup.cs 中注册它,如下所示:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IConnectionManager conn, ILoggerFactory loggerFactory)
{
app.UseMiddleware<YourMidllewareClass>();
}
在中间件类中创建 Invoke 方法。 此方法将在每个请求跳转到您的任何控制器之前被调用。
public async Task Invoke(HttpContext context)
{
string token = context.Request.Headers["Authorization"];
//do the checking
if (token == null)
{
context.Response.StatusCode = 401;
await context.Response.WriteAsync("Access denied!");
return;
}
//pass request further if correct
await _next(context);
}
据我所知,您必须在 UseMvc() 方法之前注册您的中间件,以确保您的 Invoke() 在 Mvc 管道之前被调用。
对于 ASP.NET Core 2.0,有些事情发生了变化,您还可以使用 AuthenticationHandler。
帮助您入门的良好文档位于https://docs.microsoft.com/en-us/aspnet/core/migration/1x-to-2x/identity-2x 。
我在当前项目中使用的自定义身份验证示例:
启动.配置服务:
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = "Custom Scheme";
options.DefaultChallengeScheme = "Custom Scheme";
}).AddCustomAuth(o => { });
启动.配置:
app.UseAuthentication();
最后:
internal class CustomAuthenticationHandler :
AuthenticationHandler<CustomAuthenticationOptions>
{
public CustomAuthenticationHandler(IOptionsMonitor<CustomAuthenticationOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) :
base(options, logger, encoder, clock)
{
}
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
try
{
// Your auth code here
// Followed by something like this:
return AuthenticateResult.Success(
new AuthenticationTicket(
new ClaimsPrincipal(
new ClaimsIdentity(
new List<Claim>() { new Claim(ClaimTypes.Sid, Id.ToString()) },
Scheme.Name)),
Scheme.Name));
}
catch
{
return AuthenticateResult.Fail("Error message.");
}
}
}
这样,对控制器的所有调用都将通过身份验证中间件,如有必要,您可以使用控制器上的[AllowAnonymous]
属性忽略它。
或者您可以在类或方法上使用属性来验证和检查标题元素。 视需要而定。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.