Click here to Skip to main content
15,885,546 members
Articles / Web Development / ASP.NET

An easy way to use certificates for WCF security

Rate me:
Please Sign up or sign in to vote.
4.69/5 (38 votes)
30 Apr 2007MIT12 min read 476.6K   7.2K   136  
An easy solution to use certificates on Windows Communication Foundation loading the certificates from files
using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.Security.Cryptography.X509Certificates;
using System.IdentityModel.Selectors;

namespace DevAge.ServiceModel
{
    /// <summary>
    /// A class derived from X509CertificateValidator to validate the client certificate using a specific 
    /// list of certificates.
    /// If the certificate is not in the list of valid certificate this validator try to use the default PeerOrChainTrust validator.
    /// </summary>
    public class CustomCertificateValidator : X509CertificateValidator
    {
        public CustomCertificateValidator()
        {
            mValidCertificates = new List<X509Certificate2>();
        }

        public CustomCertificateValidator(IEnumerable<X509Certificate2> validCertificates)
        {
            mValidCertificates = new List<X509Certificate2>(validCertificates);
        }

        private IList<X509Certificate2> mValidCertificates;
        public IList<X509Certificate2> ValidCertificates
        {
            get { return mValidCertificates; }
            set { mValidCertificates = value; }
        }

        public override void Validate(X509Certificate2 certificate)
        {
            // Check that there is a certificate.
            if (certificate == null)
                throw new ArgumentNullException("certificate");

            foreach (X509Certificate2 cert in ValidCertificates)
            {
                if (cert.Equals(certificate))
                    return;
            }

            X509CertificateValidator.PeerOrChainTrust.Validate(certificate);
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The MIT License


Written By
Software Developer
Italy Italy
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions