我可以在没有证书存储且不使用netsh http add sslcert的情况下在WCF中自行托管HTTPS服务吗?

时间:2011-12-23 07:32:32

标签: wcf ssl https

我正在尝试使用WebHttpBinding托管基本Web内容(HTML,javascript,json)的服务,而管理员参与最少。

到目前为止,我已经成功,唯一需要的管理员权限是在安装时间(注册服务帐户的http预留并自行创建服务)。但是,现在我遇到了SSL的问题。理想情况下,我想支持Windows证书库外的证书。我发现这篇文章 - http://www.codeproject.com/KB/WCF/wcfcertificates.aspx - 似乎表明您可以在服务主机上指定证书,但是在运行时将浏览器导航到https://localhost/Dev/MyService会产生404。

[ServiceContract]
public interface IWhoAmIService
{
    [OperationContract]
    [WebInvoke(
        Method = "GET",
        UriTemplate = "/")]
    Stream WhoAmI();
}

public class WhoAmIService : IWhoAmIService
{
    public Stream WhoAmI()
    {
        string html = "<html><head><title>Hello, world!</title></head><body><p>Hello from {0}</p></body></html>";
        html = string.Format(html, WindowsIdentity.GetCurrent().Name);

        WebOperationContext.Current.OutgoingResponse.ContentType = "text/html";

        return new MemoryStream(Encoding.UTF8.GetBytes(html));
    }
}

static void Main(string[] args)
{
    ServiceHost host = new ServiceHost(typeof(WhoAmIService), new Uri("https://localhost:443/Dev/WhoAmI"));
    host.Credentials.ServiceCertificate.Certificate = new X509Certificate2(@"D:\dev\Server.pfx", "private");

    WebHttpBehavior behvior = new WebHttpBehavior();
    behvior.DefaultBodyStyle = WebMessageBodyStyle.Bare;
    behvior.DefaultOutgoingResponseFormat = WebMessageFormat.Json;
    behvior.AutomaticFormatSelectionEnabled = false;

    WebHttpBinding secureBinding = new WebHttpBinding();
    secureBinding.Security.Mode = WebHttpSecurityMode.Transport;
    secureBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;

    ServiceEndpoint secureEndpoint = host.AddServiceEndpoint(typeof(IWhoAmIService), secureBinding, "");
    secureEndpoint.Behaviors.Add(behvior);

    host.Open();
    Console.WriteLine("Press enter to exit...");
    Console.ReadLine();
    host.Close();
}

如果我将绑定安全性更改为none而基本uri以http开头,那么它可以正常运行。这篇文章似乎表明需要执行一个额外的命令来注册带有netsh端口的证书(http://social.msdn.microsoft.com/Forums/en-US/wcf/thread/6907d765-7d4c-48e8 -9e29-3ac5b4b9c405 /)。当我尝试这个时,它失败并出现一些模糊的错误(1312)。

C:\Windows\system32>netsh http add sslcert ipport=0.0.0.0:443 certhash=0b740a29f
29f2cc795bf4f8730b83f303f26a6d5 appid={00112233-4455-6677-8899-AABBCCDDEEFF}

SSL Certificate add failed, Error: 1312
A specified logon session does not exist. It may already have been terminated.

如何在没有Windows证书存储的情况下使用HTTPS托管此服务?

1 个答案:

答案 0 :(得分:7)

这是不可能的。 HTTPS是在操作系统级别(http.sys内核驱动程序)上提供的 - 它与在证书库中提供HTTP预留和操作系统级别需求证书相同。您必须使用netsh将证书分配给选定端口并允许访问私钥。

本文使用来自文件的证书,因为它不使用HTTPS。它使用消息安全性和消息安全性(除非您使用REST服务和webHttpBinding开发自己的非互操作性)。

使用HTTPS实现此功能的唯一方法是不使用依赖于http.sys的内置HTTP处理=您必须自己实现整个HTTP并为WCF准备新的HTTP通道,否则您将不得不找到这样的实现