我有一个.NET项目,该项目使用以下配置来调用Web服务:
<endpoint address="URL" binding="wsHttpBinding"
bindingConfiguration="WSHttpBinding_MyService" contract="TokenServiceDev.MyService" name="WSHttpBinding_MyService">
<identity>
<certificate encodedValue="xxxx"/>
</identity>
</endpoint>
您可以看到<identity>
节点指定了X509CertificateEndpointIdentity。
我正在将该项目迁移到.NET Core,因此,鉴于不支持ServiceModel.Configuration
的事实,我需要以编程方式设置此配置。
我一直在寻找一些指南,尽管this是.NET Framework的“指南”,但我希望我可以轻松地将其调整为.NET Core。不幸的是,我找不到指定所需身份的方法。
我应该怎么做才能在.NET Core中指定X509证书终结点身份?
答案 0 :(得分:0)
对于对此感兴趣的任何人,我都使用.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 Core 3.1显然支持与您提供的链接中提到的类似,如此GitHub issue所示。