gpt4 book ai didi

c# - 如何使用带有客户端证书的 (Microsoft.AspNetCore.TestHost)TestServer

转载 作者:太空宇宙 更新时间:2023-11-03 13:19:43 25 4
gpt4 key购买 nike

在 .net core api 中启用证书身份验证会导致 TestServer 在集成测试中始终返回 403-Forbidden(尽管请求中使用了证书)。

我尝试更改 TestClientProvider 中的 CertificateValidationService,但似乎在到达用户定义的身份验证逻辑之前证书验证失败。 当部署在 Azure 中时,该服务可使用客户端证书正常工作。

我错过了什么吗?有什么方法可以将 TestServer 与受客户端证书保护的 API 一起使用吗?

复制

  1. 在 .NET Core API 中启用证书身份验证 https://learn.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. 在您的 api 上使用“授权”属性
// WeatherForecastController.cs  (VS 2019 template)
[ApiController]
[Route("api/weather")]
[Authorize]
public class WeatherForecastController : ControllerBase
{
...
}
  1. 使用 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);
}
}

最佳答案

根据 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";
});

关于c# - 如何使用带有客户端证书的 (Microsoft.AspNetCore.TestHost)TestServer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59647476/

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