カスタム サービス動作を作成すると、構成からアプリケーション ポリシーとサブジェクト名を提供し、証明書ストアで 2 つの連続した検索を実行できます。
public class ServerCertificateServiceBehavior : IServiceBehavior
{
private X509Certificate2 certificate;
public ServerCertificateServiceBehavior(StoreName storeName, StoreLocation storeLocation, string subjectName, string applicationPolicy)
{
X509Store store = new X509Store(storeName, storeLocation);
store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
certificate = store
.Certificates
.Find(X509FindType.FindByApplicationPolicy, applicationPolicy, false)
.Find(X509FindType.FindBySubjectName, subjectName, false)
.Cast<X509Certificate2>()
.SingleOrDefault();
}
public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters)
{
serviceHostBase.Credentials.ServiceCertificate.Certificate = this.certificate;
}
public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase) { }
public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase) { }
}
ExtensionElement :
public class ServerCertificateServiceBehaviorExtensionElement : BehaviorExtensionElement
{
[ConfigurationProperty("applicationPolicy", IsRequired = true)]
public string ApplicationPolicy
{
get
{
return (string)base["applicationPolicy"];
}
set
{
base["applicationPolicy"] = value;
}
}
[ConfigurationProperty("subjectName", IsRequired = true)]
public string SubjectName
{
get
{
return (string)base["subjectName"];
}
set
{
base["subjectName"] = value;
}
}
[ConfigurationProperty("storeLocation", DefaultValue = 2)]
public StoreLocation StoreLocation
{
get
{
return (StoreLocation)base["storeLocation"];
}
set
{
base["storeLocation"] = value;
}
}
[ConfigurationProperty("storeName", DefaultValue = 5)]
public StoreName StoreName
{
get
{
return (StoreName)base["storeName"];
}
set
{
base["storeName"] = value;
}
}
public override Type BehaviorType
{
get { return typeof(ServerCertificateServiceBehavior); }
}
protected override object CreateBehavior()
{
return new ServerCertificateServiceBehavior(
this.StoreName,
this.StoreLocation,
this.SubjectName,
this.ApplicationPolicy);
}
}
構成は次のようになります。
<behaviors>
<serviceBehaviors>
<behavior name="YourServiceBehaviorConfiguration">
<!-- ... -->
<serverCertificate storeLocation="LocalMachine"
storeName="My"
subjectName="host.domain.com"
applicationPolicy="1.3.6.1.5.5.7.3.1" />
</behavior>
</serviceBehaviors>
</behaviors>
<extensions>
<behaviorExtensions>
<add name="serverCertificate" type="Extensions.ServerCertificateServiceBehaviorExtensionElement, Extensions, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"/>
</behaviorExtensions>
</extensions>