You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将含ssl.LoadClientCertAsync的OWIN中间件转为ASP.NET Core版本?

ASP.NET Core 版本客户端证书验证中间件实现

核心转换要点

  • 替换OWIN的ssl.LoadClientCertAsync:使用ASP.NET Core内置的Connection.GetClientCertificateAsync()异步加载客户端证书
  • 替换OWIN的ssl.ClientCertificate:使用Connection.ClientCertificate(或异步获取后的结果)
  • 替换OWIN的ssl.ClientCertificateErrors:通过ITlsConnectionFeature获取证书验证错误集合

完整中间件代码

using Microsoft.AspNetCore.Http.Features;
using System.Security.Cryptography.X509Certificates;
using System.Linq;

public class ClientCertificateMiddleware
{
    private readonly RequestDelegate _next;

    public ClientCertificateMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        // 异步加载客户端证书,替代原OWIN的ssl.LoadClientCertAsync逻辑
        var clientCert = await context.Connection.GetClientCertificateAsync();

        // 验证证书是否存在
        if (clientCert == null)
        {
            context.Response.StatusCode = StatusCodes.Status403Forbidden;
            return;
        }

        // 将证书主题信息存入请求上下文(替代原OwinMannatechClientInfo的存储逻辑)
        context.Items["OwinMannatechClientInfo"] = clientCert.Subject;

        // 获取证书验证错误集合,替代原OWIN的ssl.ClientCertificateErrors
        var tlsFeature = context.Features.Get<ITlsConnectionFeature>();
        if (tlsFeature?.ClientCertificateErrors?.Any() == true)
        {
            context.Response.StatusCode = StatusCodes.Status403Forbidden;
            return;
        }

        // 继续执行后续中间件
        await _next(context);
    }
}

// 扩展方法,方便在管道中注册中间件
public static class ClientCertificateMiddlewareExtensions
{
    public static IApplicationBuilder UseClientCertificateValidation(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<ClientCertificateMiddleware>();
    }
}

部署配置要点

Kestrel 配置

需要在Program.cs中配置Kestrel接受客户端证书:

var builder = WebApplication.CreateBuilder(args);

builder.WebHost.ConfigureKestrel(options =>
{
    options.ConfigureHttpsDefaults(httpsOptions =>
    {
        // 根据业务需求选择模式:RequireCertificate/Allow/NoCertificate
        httpsOptions.ClientCertificateMode = ClientCertificateMode.RequireCertificate;
    });
});

var app = builder.Build();

// 在路由处理前注册证书验证中间件
app.UseHttpsRedirection();
app.UseClientCertificateValidation();

app.MapControllers();

app.Run();

IIS 部署注意

如果部署在IIS上,需在站点SSL设置中启用「要求SSL」和「接受客户端证书」,并确保IIS将证书信息传递给ASP.NET Core应用。

内容的提问来源于stack exchange,提问作者Yola

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 12:22:13