Click here to Skip to main content
15,894,630 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.Configuration;
using System.Security.Cryptography.X509Certificates;

namespace Certificate.Configuration
{
    public class CertificatesSection : ConfigurationSection
    {
        internal const string serializedCertificateConfigName = "certificate";
        internal const string trustedCertificatesConfigName = "trustedCertificates";

        [ConfigurationProperty(serializedCertificateConfigName, IsRequired=true)]
        public String SerializedCertificate
        {
            get
            {
                return (String)this[serializedCertificateConfigName];
            }

            set
            {
                this[serializedCertificateConfigName] = value;
            }
        }

        public X509Certificate2 Certificate
        {
            get
            {
                X509Certificate2 result = null;
                if (string.IsNullOrWhiteSpace(this.SerializedCertificate))
                {
                    throw new ConfigurationErrorsException("Please provide Certificate!");
                }
                try
                {
                    var serializer = new CertificateSerializer();
                    result = serializer.Deserialize(this.SerializedCertificate);
                }
                catch (Exception ex)
                {
                    throw new ConfigurationErrorsException(string.Format("Error deserializing the provider certificate: {0}",
                        ex.Message), ex);
                }
                return result;
            }
        }

        [ConfigurationProperty(trustedCertificatesConfigName)]
        public TrustedCertificateInfoCollection TrustedCertificates
        {
            get
            {
                return (TrustedCertificateInfoCollection)base[trustedCertificatesConfigName];
            }
        }
    }
}

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