Click here to Skip to main content
15,897,518 members
Articles / Security

Securing WCF Service with Self Signed Certificates Programmatically

Rate me:
Please Sign up or sign in to vote.
4.96/5 (15 votes)
21 Apr 2015CPOL2 min read 38.5K   132   30  
Securing a WCF Service with self signed certificates programmatically
using System;
using System.Collections.Generic;
using System.IdentityModel.Selectors;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Security;

namespace Certificate
{
    public class CertificateValidator : X509CertificateValidator
    {
        private readonly IEnumerable<string> trustedThumbprints;

        public CertificateValidator(IEnumerable<string> thumbprints)
        {
            this.trustedThumbprints = thumbprints;
        }

        public override void Validate(X509Certificate2 certificate)
        {
            //check if there is a certificate in the request
            if (certificate == null)
            {
                throw new SecurityException("Missing certificate");
            }
            //check if the certificate thumbprint is in the list of the trusted ones
            if (!trustedThumbprints.Any(thumbprint => thumbprint.Equals(certificate.Thumbprint)))
            {
                throw new SecurityException("The provided certificate is not trusted!");
            }
        }
    }
}

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 Code Project Open License (CPOL)


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

Comments and Discussions