简体   繁体   English

如何使用 (Microsoft.AspNetCore.TestHost)TestServer 和客户端证书

[英]How to use (Microsoft.AspNetCore.TestHost)TestServer with Client Certificate

Enabling certificate authentication in .net core api causes the TestServer to always return 403-Forbidden in integration tests (despite certificate used in request).在 .net core api 中启用证书身份验证会导致 TestServer 在集成测试中始终返回 403-Forbidden(尽管请求中使用了证书)。

I tried altering the CertificateValidationService in TestClientProvider but it seems the certificate validation is failing before reaching the user-defined authentication logic.我尝试更改 TestClientProvider 中的 CertificateValidationService 但似乎证书验证在到达用户定义的身份验证逻辑之前失败。 The service is working properly with client certificate when deployed in Azure.在 Azure 中部署时,该服务与客户端证书一起正常工作。

Am I missing something?我错过了什么吗? Is there any way to use TestServer with an API protected by client certificate?有没有办法将 TestServer 与受客户端证书保护的 API 一起使用?

To Reproduce再现

  1. Enable certificate authentication in .NET Core API https://docs.microsoft.com/en-us/aspnet/core/security/authentication/certauth?view=aspnetcore-3.1在 .NET Core API 中启用证书身份验证https://docs.microsoft.com/en-us/aspnet/core/security/authentication/certauth?view=aspnetcore-3.1
// Startup.cs
    ...
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton<CertificateValidationService>();
        services.AddAuthentication(
            CertificateAuthenticationDefaults.AuthenticationScheme).AddCertificate(options =>
        {
            ...
        });
        services.AddAuthorization();
        services.AddControllers();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger<Startup> logger)
    {
        ...

        app.UseRouting();

        app.UseCertificateForwarding();
        app.UseAuthentication();
        app.UseAuthorization();
        ...

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
  1. Use "authorize" attribute on your api在您的 api 上使用“授权”属性
// WeatherForecastController.cs  (VS 2019 template)
    [ApiController]
    [Route("api/weather")]
    [Authorize]
    public class WeatherForecastController : ControllerBase
    {
    ...
    }
  1. Write integration test using Microsoft.AspNetCore.TestHost使用 Microsoft.AspNetCore.TestHost 编写集成测试
// IntegrationTests/ClientCertificateTests.cs
    [Fact]
    public async void GivenValidCertificate_PerformGet_ExpectSuccess()
    {
        X509Certificate2 validClientCertificate;
        using (var certStore = new X509Store(StoreName.My, StoreLocation.CurrentUser))
        {
            certStore.Open(OpenFlags.ReadOnly);
            validClientCertificate = certStore.Certificates.Find(X509FindType.FindByTimeValid, DateTime.Now, true)[0];
        }

        using (var server = new TestClientProvider(ignoreCertificate: false).Server)
        {
            // Act
            var result = await server.SendAsync(context =>
            {
                context.Connection.ClientCertificate = validClientCertificate;
                context.Request.Method = "GET";
                context.Request.Path = "/api/weather";
            });

            // Assert
            Assert.Equal(200, result.Response.StatusCode);
        }
    }

According to https://github.com/dotnet/aspnetcore/issues/18177 , I also had to to set the request scheme to "https", which worked for me.根据https://github.com/dotnet/aspnetcore/issues/18177 ,我还必须将请求方案设置为“https”,这对我有用。

    var result = await server.SendAsync(context =>
    {
        context.Connection.ClientCertificate = validClientCertificate;
        context.Request.Method = "GET";
        context.Request.Scheme = "https";
        context.Request.Path = "/api/weather";
    });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在不使用Microsoft.AspNetCore.TestHost中包含的TestServer的情况下运行Kestrel进行测试 - Running Kestrel for testing without using the TestServer included in Microsoft.AspNetCore.TestHost 使用 Microsoft.AspNetCore.TestHost 热调试 playwright-do.net 测试 - Hot to debug playwright-dotnet tests with Microsoft.AspNetCore.TestHost 从Microsoft.AspNetCore.TestHost.TestServer获取连接字符串值 - Get connection string value from Microsoft.AspNetCore.TestHost.TestServer 如何使用Microsoft.Rest.ServiceClient &lt;&gt;与客户端证书? - How to use Microsoft.Rest.ServiceClient<> with client certificate? Microsoft.AspNetCore.Authentication.Certificate.CertificateAuthenticationHandler 证书验证失败 - Microsoft.AspNetCore.Authentication.Certificate.CertificateAuthenticationHandler Certificate validation failed 依赖项注入不适用于ASPNETCore.TestHost - Dependancy Injection not working with ASPNETCore.TestHost 用TestHost测试AspNetCore,找不到WebApplicationTestFixture类 - AspNetCore testing with TestHost, WebApplicationTestFixture class not found Microsoft.Owin.Testing.TestServer不能与Fiddler一起使用 - Microsoft.Owin.Testing.TestServer cannot use with Fiddler 如何让 TestServer 使用不同的 appsettings 文件? - How to get a TestServer to use a different appsettings file? 如何使用 Microsoft.AspNetCore.Authentication 在 C# 中设置 OpenIdConnect 客户端身份验证方法(从配置作为参数)? - How to set OpenIdConnect Client Authentication Method (from a config as a parameter) in C# using Microsoft.AspNetCore.Authentication?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM