开发者

Display service's certificate in WCF client?

开发者 https://www.devze.com 2023-01-20 08:20 出处:网络
I\'ve got a WCF client and service. The service is configured to use a certificate for encryption. This is all working fine. We\'re using self-signed certificates for testing.

I've got a WCF client and service. The service is configured to use a certificate for encryption. This is all working fine. We're using self-signed certificates for testing.

Except that one of my QA guys has deleted the certificate from his client PC and he can still connect to the service.

This leads to my question:

In Internet Explorer (and other browsers), when you're connected via HTTPS, you can see the server's certificate by clicking on the padlock ic开发者_Go百科on. I'd like to do something similar in my WCF client, so that the user can verify the server's identity. Is there a way in my WCF client to get hold of the server certificate and to display it?


One way to achieve this is by using a custom certificate validator (in which case the server cert will be passed in to the Validate method, and from there you can do what you like with it (i.e. save the certificate somewhere the client can use, and then validate it using one of the default validators))

public class MyX509CertificateValidator : X509CertificateValidator
{
    private readonly X509CertificateValidationMode _validationMode;
    private readonly WcfClient _client;

    public MyX509CertificateValidator(WcfClient client, X509CertificateValidationMode validationMode)
    {
        _client = client;
        _validationMode = validationMode;
    }

    public override void Validate(X509Certificate2 certificate)
    {
        if (certificate == null)
        {
            throw new ArgumentNullException("certificate");
        }

        _client.ServerCertificate = certificate;

        switch (_validationMode)
        {
            case X509CertificateValidationMode.None:
                None.Validate(certificate);
                return;
            case X509CertificateValidationMode.PeerOrChainTrust:
                PeerOrChainTrust.Validate(certificate);
                return;
            case X509CertificateValidationMode.PeerTrust:
                PeerTrust.Validate(certificate);
                return;
            default:
                ChainTrust.Validate(certificate);
                return;
        }

    }
}


The encryption will use the server side certificate, just like it does for a https site.

You could use the client certificates for authentication, but this is something else.

0

精彩评论

暂无评论...
验证码 换一张
取 消