|
using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Security;
using System.Security.Cryptography.X509Certificates;
namespace DevAge.ServiceModel
{
/// <summary>
/// A class that derive from the ServiceHost system class to automatically set the
/// server certificate used for service authentication.
/// This class set the Credentials.ServiceCertificate.Certificate property override any certificate configuration.
/// Consider anyway that you must correctly configure the binding security.
/// </summary>
public class CertificateServiceHost : ServiceHost
{
public CertificateServiceHost(Type serviceType, Uri[] baseAddresses)
: base(serviceType, baseAddresses)
{
}
protected override void ApplyConfiguration()
{
base.ApplyConfiguration();
//Check if there is a valid configuration section
Configuration.Section section = Configuration.Section.GetSection();
if (section == null || section.Services == null)
return;
//Check if there is a valid configuration for this service
Configuration.ServiceElement element = section.Services.GetElementByKey(Description.Name);
if (element == null)
return;
X509Certificate2 serverCertificate = element.GetServerCertificate();
//Set the server certificate
if (serverCertificate != null)
this.Credentials.ServiceCertificate.Certificate = serverCertificate;
//Set the client certificates and the validator
if (string.IsNullOrEmpty(element.ClientCertificates) == false)
{
X509ClientCertificateAuthentication authentication =
this.Credentials.ClientCertificate.Authentication;
authentication.CertificateValidationMode =
System.ServiceModel.Security.X509CertificateValidationMode.Custom;
authentication.CustomCertificateValidator =
new CustomCertificateValidator(element.GetClientCertificates());
}
}
}
}
|
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.
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.