经过几天的测试后,我发现使用身份验证创建WCF Web服务的唯一方法是将证书放在localmachine / trustedpeople证书库中。主持人不会为我这样做。您知道如何在不在该商店中放置证书的情况下启用WCF身份验证吗?有没有其他方法可以让WCF安全工作在共享主机上?
我已经在codeproject上使用了一个示例,该示例将证书放在app_data中,但我无法让它工作。
答案 0 :(得分:3)
我在本地IIS上做了一些非常简单的测试。我用单一方法提供非常简单的服务。要公开服务,我使用此配置:
<configuration>
<appSettings>
<add key="CertificatePath" value="D:\Applications\CertificateFromFile\App_Data\ServerCert.pfx" />
<add key="CertificatePassword" value="password" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="CertificateFromFile.MyPasswordValidator, CertificateFromFile" />
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>
<protocolMapping>
<clear />
<add scheme="http" binding="wsHttpBinding" />
</protocolMapping>
<bindings>
<wsHttpBinding>
<binding>
<security mode="Message">
<message clientCredentialType="UserName" establishSecurityContext="false" negotiateServiceCredential="false" />
</security>
</binding>
</wsHttpBinding>
</bindings>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true">
<serviceActivations>
<add service="CertificateFromFile.MyService" factory="CertificateFromFile.MyServiceHostFactory" relativeAddress="Service.svc" />
</serviceActivations>
</serviceHostingEnvironment>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
</system.webServer>
</configuration>
配置定义:
加载证书的神奇之处在于自定义服务主机和服务主机工厂:
namespace CertificateFromFile
{
public class MyServiceHostFactory : ServiceHostFactory
{
protected override System.ServiceModel.ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
{
string path = ConfigurationManager.AppSettings["CertificatePath"];
string password = ConfigurationManager.AppSettings["CertificatePassword"];
return new MyServiceHost(serviceType, path, password, baseAddresses);
}
}
public class MyServiceHost : ServiceHost
{
private readonly string _certificatePath;
private readonly string _certificatePassword;
public MyServiceHost(Type serviceType, string certificatePath, string certificatePassword, params Uri[] baseAddresses)
: base(serviceType, baseAddresses)
{
_certificatePath = certificatePath;
_certificatePassword = certificatePassword;
}
protected override void OnOpening()
{
base.OnOpening();
var certificate = new X509Certificate2(_certificatePath, _certificatePassword);
var credentials = Description.Behaviors.Find<ServiceCredentials>();
credentials.ServiceCertificate.Certificate = certificate;
}
}
}