Tac*_*yon 2 c# asp.net-core .net-5
我需要在 .NET 5 Web API 中的某些端点上实现客户端证书身份验证。因此,我不想按照 MS 文档中所述跨所有端点启用 HTTPS 。我在本地计算机上使用 Kestrel,而不是 IIS Express 或 IIS。
我尝试了以下三种方法,但都没有成功:
var clientCertHeaders = context.HttpContext.Request.Headers;
Run Code Online (Sandbox Code Playgroud)
此命令返回请求的正常标头,但不返回证书。
var clientCert = context.HttpContext.Connection.ClientCertificate;
var clientCertAsync = context.HttpContext.Connection.GetClientCertificateAsync().Result;
Run Code Online (Sandbox Code Playgroud)
这两个都返回 null。
我尝试将以下内容应用到我的服务中:
services.AddCertificateForwarding(options =>
{
options.CertificateHeader = "X-SSL-CERT";
options.HeaderConverter = (headerValue) =>
{
X509Certificate2 clientCertificate = null;
if(!string.IsNullOrWhiteSpace(headerValue))
{
var bytes = Encoding.UTF8.GetBytes(headerValue);
clientCertificate = new X509Certificate2(bytes);
}
return clientCertificate;
};
});
Run Code Online (Sandbox Code Playgroud)
即使在我的服务中启用了该功能,我也无法检索客户端证书。
我正在使用 Postman 向 API 请求发出请求。
您需要将 Kestrel 配置为允许客户端证书。program.cs默认值是ClientCertificateMode.NoCertificate这样,ConfigureWebHostDefaults您需要将其更改为ClientCertificateMode.AllowCertificate。
这是您发送给我的文档中经过编辑的代码块:
public static IHostBuilder CreateHostBuilder(string[] args)
{
return Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
webBuilder.ConfigureKestrel(o =>
{
o.ConfigureHttpsDefaults(o =>
o.ClientCertificateMode =
ClientCertificateMode.AllowCertificate);
});
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5191 次 |
| 最近记录: |