使用自己的身份验证、授权时,如何在 ASP.NET 核心健康检查调用中检查用户代理?

How to check user-agent in ASP.NET Core health check calls when using own authentication, authorization?

我使用了 的公认答案,但要求有一处不同:

我的应用程序没有使用应用程序服务身份验证和授权。因此,我需要根据 documentation.

允许匿名访问健康检查

以下是对 Startup.cs

的更改
             //other services

            services.AddHttpContextAccessor();
            services.AddScoped<IAuthorizationHandler, UserAgentAuthorizationHandler>();
            services.AddHealthChecks()
                .AddCheck<HealthCheckFoo>("health_check_foo")
                .AddCheck<HealthCheckBar>("health_check_bar");

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

            //...
            
            app.UseEndpoints(endpoints =>
             {
                 //other endpoints...

                endpoints.MapHealthChecks("/health", new HealthCheckOptions { AllowCachingResponses = false })
                         .RequireAuthorization("HealthCheckPolicy");
                         .WithMetadata(new AllowAnonymousAttribute());

我的预期是在本地测试时,https://localhost:5001/health return 报错。它没有。

看起来您的启动 class 在 endpoints.MapHealthChecks 上添加了一个 RequireAuthorization 但同时您还添加了 AllowAnonymousAttribute.

试试:

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