Working with Certificates – Part IV, Custom X509 validation

April 8th, 2009 | Tags:

In my previous article, I showed how you could embed a certificate as a managed resource in your application.

Today, I will demonstrate how you can implement your own custom certificate validation for WCF.

There are many scenarios where you would want to implement your own certificate validation mechanics. For instance, it might not be enough that the certificate is just trusted, it might be required to have a specific subject name, or issuer.

To implement your own custom X509 certificate validation, you inherit from the class X509CertificateValidator in the System.IdentityModel.Selectors namespace, like this:

/// <summary>
/// Implements the validator for X509 certificates.
/// </summary>
internal class MyX509Validator : X509CertificateValidator
{
  /// <summary>
  /// Validates a certificate.
  /// </summary>
  /// <param name="certificate">The certificate to
  /// validate.</param>
  public override void Validate(X509Certificate2 certificate)
  {
      // validate argument
      if (certificate == null)
        throw new ArgumentNullException("certificate");

      // check if the name of the certifcate matches
      if (certificate.SubjectName.Name != "CN=Tempus")
        throw new SecurityTokenValidationException(
          "Certificated was not issued by trusted issuer");
    }
}

Then, you hook it up on the proxy instance like this:

SampleClient client = new SampleClient();
client.ClientCredentials.ServiceCertificate.Authentication.
  CertificateValidationMode =
    X509CertificateValidationMode.Custom;
client.ClientCredentials.ServiceCertificate.Authentication.
  CustomCertificateValidator = new MyX509Validator();

// Make a service call
client.Foo("bar");

You can, of course. hook it up in the .config file instead, like this:

<behaviors>
  <endpointBehaviors>
    <behavior name="CustomX509">
      <clientCredentials>
        <serviceCertificate>
          <authentication certificateValidationMode="Custom"
            customCertificateValidatorType=
            "SampleConsumer.MyX509Validator, SampleConsumer"/>
        </serviceCertificate>
      </clientCredentials>
    </behavior>
  </endpointBehaviors>
</behaviors>

That’s all there’s to it!

Technorati Tags: ,,,,
No comments yet.