【问题标题】:Specify web service X509 certificate endpoint identity in .NET Core在 .NET Core 中指定 Web 服务 X509 证书端点标识
【发布时间】:2018-09-18 09:23:25
【问题描述】:

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

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

如您所见,X509CertificateEndpointIdentity 由 &lt;identity&gt; 节点指定。

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

我一直在寻找一些指导方针,尽管 this 是 .NET Framework 的“指南”,但我希望我可以轻松地将其调整为 .NET Core。不幸的是,我找不到指定我需要的身份的方法。

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

【问题讨论】:

  • 我还没有使用过.NET core,虽然有几种方法可以在代码中设置证书身份

标签: c# .net wcf .net-core


【解决方案1】:

对于任何对此感兴趣的人,我刚刚使用 .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();

如此 GitHub issue 所示,.NET Core 3.1 显然支持与您提供的链接中提到的内容类似的内容。

【讨论】:

    猜你喜欢
    • 2011-08-21
    • 1970-01-01
    • 1970-01-01
    • 2018-05-25
    • 2018-11-19
    • 1970-01-01
    • 1970-01-01
    • 2021-12-30
    • 1970-01-01
    相关资源
    最近更新 更多