gpt4 book ai didi

asp.net-core - 如何在 ASP.NET Core 健康检查调用 (MapHealthChecks) 中检查用户代理?

转载 作者:行者123 更新时间:2023-12-03 08:25:58 24 4
gpt4 key购买 nike

https://learn.microsoft.com/en-us/azure/app-service/monitor-instances-health-check值得注意的是

Large enterprise development teams often need to adhere to security requirements for exposed APIs. To secure the Health check endpoint, you should first use features such as IP restrictions, client certificates, or a Virtual Network to restrict application access. You can secure the Health check endpoint by requiring the User-Agent of the incoming request matches ReadyForRequest/1.0. The User-Agent can't be spoofed since the request would already secured by prior security features.

在实践中如何检查用户代理?我正在考虑代码

app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapHealthChecks("/health", new HealthCheckOptions { AllowCachingResponses = false });
});

然后在 Azure 中,WebApp 会在回复之前检查它是来自 Azure 服务的调用,而不是来自公共(public) Internet 的调用(否则直接丢弃调用)。不过,我知道有更好的方法可以在边缘做到这一点。

我认为我想到的选择是写一个 middlware component请检查 URL 和代理。虽然也许我错过了一些明显的事情,但这不是方法? :)

最佳答案

您可以创建 policy它执行用户代理需求验证

public class UserAgentRequirement : IAuthorizationRequirement
{
public string UserAgent { get; }

public UserAgentRequirement(string userAgent)
{
UserAgent = userAgent;
}
}

public class UserAgentAuthorizationHandler : AuthorizationHandler<UserAgentRequirement>
{
private readonly IHttpContextAccessor httpContextAccessor;

public UserAgentAuthorizationHandler(IHttpContextAccessor httpContextAccessor)
{
this.httpContextAccessor = httpContextAccessor;
}

protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, UserAgentRequirement requirement)
{
var httpContext = httpContextAccessor.HttpContext;

var agent = httpContext.Request.Headers["User-Agent"];
if (agent == requirement.UserAgent)
{
context.Succeed(requirement);
}
else
{
context.Fail();
}
return Task.CompletedTask;
}
}

不要忘记注册IHttpContextAccessorUserAgentAuthorizationHandler。在Startup.cs

services.AddHttpContextAccessor();
services.AddScoped<IAuthorizationHandler, UserAgentAuthorizationHandler>();

services.AddAuthorization(options =>
{
//...
options.AddPolicy("HealthCheckPolicy", builder =>
{
builder.AddRequirements(new UserAgentRequirement("ReadyForRequest/1.0"));
});
});

//...

app.UseEndpoints(endpoints =>
{
endpoints
.MapHealthChecks("/health", new HealthCheckOptions { AllowCachingResponses = false })
.RequireAuthorization("HealthCheckPolicy");
//...
});

关于asp.net-core - 如何在 ASP.NET Core 健康检查调用 (MapHealthChecks) 中检查用户代理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66654787/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com