代码之家  ›  专栏  ›  技术社区  ›  Matteo Umili

在.NET Core中指定web服务X509证书终结点标识

  •  0
  • Matteo Umili  · 技术社区  · 6 年前

    我有一个使用此配置调用web服务的.NET项目:

      <endpoint address="URL" binding="wsHttpBinding"
        bindingConfiguration="WSHttpBinding_MyService" contract="TokenServiceDev.MyService" name="WSHttpBinding_MyService">
        <identity>
          <certificate encodedValue="xxxx"/>
        </identity>
      </endpoint>
    

    如您所见,X509CertificateEndpointIdentity由 <identity> 节点。

    我正在将此项目迁移到.NET Core,因此,考虑到 ServiceModel.Configuration 不支持,我需要以编程方式设置此配置。

    我在找一些指导方针,尽管 this 是.NET框架的“指南”,我希望可以轻松地将其调整为.NET核心。不幸的是,我找不到一种方法来指定我需要的身份。

    如何在.NET Core中指定X509证书终结点标识?

    0 回复  |  直到 6 年前
        1
  •  0
  •   chrisc    5 年前

    对于任何对此感兴趣的人,我只是用.NET Core 2.1测试了它,并成功地使其工作如下。

    定义客户端 X509CertificateValidator

    public class MyCertificateValidator : X509CertificateValidator
    {
        private readonly string _allowedCertificateEncodedValue;
    
        public MyCertificateValidator(string allowedCertificateEncodedValue)
        {
            _allowedCertificateEncodedValue = allowedCertificateEncodedValue ?? throw new ArgumentNullException("allowedCertificateEncodedValue");
        }
        public override void Validate(X509Certificate2 certificate)
        {
            if (certificate == null)
            {
                throw new ArgumentNullException("certificate");
            }
    
            var allowedCertificateEncodedValue = Convert.ToBase64String(certificate.RawData);
            if (_allowedCertificateEncodedValue != allowedCertificateEncodedValue)
            {
                throw new SecurityTokenValidationException("Certificate does not match the provided encoded value.");
            }
        }
    }
    

    创建客户机时使用验证器。

    var remoteAddress = new EndpointAddress("https://localhost:44300/MyService.svc");
    _myServiceClient = new MyServiceClient(MyServiceClient.EndpointConfiguration.WSHttpBinding_IMyService, remoteAddress);
    _myServiceClient.ClientCredentials.ServiceCertificate.SslCertificateAuthentication =
        new X509ServiceCertificateAuthentication()
        {
            CertificateValidationMode = X509CertificateValidationMode.Custom,
            CustomCertificateValidator = new MyCertificateValidator(CertificateEncodedValue)
        };
    
    await _myServiceClient.OpenAsync();
    

    与您提供的链接中提到的类似的东西显然将在.NET Core3.1中得到支持,如GitHub所示 issue