首页 > 解决方案 > WCF 使用凭据和 IIS 以编程方式启用 TLS

问题描述

我正在开发一项服务以在 WCF 中使用基于 SSL/TLS 凭据的安全性。端点将使用 IIS 和 HTTPS 命中。基本的 HTTP 绑定可以正常工作,但是一旦我尝试添加凭据,我就会不断收到配置错误。我已经花了几天的时间阅读了很多文章,但没有成功。

我试过了

// 后面的代码

    public class specificService : myServiceType
    {
        public static void Configure(ServiceConfiguration configuration)
        {
            // define https binding (I think it should be BasicHttpsBinding as opposed to BasicHttpBinding which also supports TLS but I am unsure)
            var httpsBinding = new BasicHttpsBinding
            {
                MaxReceivedMessageSize = int.MaxValue,
                Security = new BasicHttpsSecurity
                {
                    Mode = BasicHttpsSecurityMode.Transport,
                    Transport = new HttpTransportSecurity
                    {
                        ClientCredentialType = HttpClientCredentialType.Certificate
                    }
                }
            };

            configuration.AddServiceEndpoint(typeof(myServiceType), httpsBinding, string.Empty);
              configuration.Description.Endpoints.Find(typeof(myServiceType))?.EndpointBehaviors.Add(new myNamespace.MyCustomEndpointBehavior());
            configuration.Description.Behaviors.Add(new ServiceDebugBehavior { IncludeExceptionDetailInFaults = true });
            configuration.Description.Behaviors.Add(new ServiceMetadataBehavior { HttpGetEnabled = true });


            // Do I need to explicitly add my certificate?
            X509Certificate2 myCert = ... get cert from local machine store
            configuration.Credentials.ServiceCertificate.Certificate = myCert;
        }


/* myServiceType interface */
    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
    [System.ServiceModel.ServiceContractAttribute(Namespace="http://somenamespace", ConfigurationName="someothernamespace.Services.myServiceType")]
    public interface myServiceType
    {
        // CODEGEN: Generating message contract since the operation specificAction is neither RPC nor document wrapped.
        [System.ServiceModel.OperationContractAttribute(Action="http://somenamespace/specificAction")]
        someothernamespace.Services.specificActionResponse specificAction(someothernamespace.Services.specificAction request);
    }

我不断收到“配置错误”,但没有详细说明我到底做错了什么。我尝试了不同的实现(wsHttpBindings)但没有成功。

标签: c#wcfsslcredentials

解决方案


虽然 WCF4.5 宣布我们可以在服务实现类中使用静态 Configure 方法来设置服务,但我建议您在配置文件中配置服务。它简洁明了。

// 我需要显式添加我的证书吗?

您不需要设置证书,因为传输安全模式需要 IIS 站点绑定模块中的 https 基地址。
此外,如果您想使用证书对客户端进行身份验证,请参考以下链接。
https://docs.microsoft.com/en-us/dotnet/framework/wcf/feature-details/transport-security-with-certificate-authentication
我们应该在开始时建立服务器和客户端之间的信任关系,并且那么客户端应该提供服务器信任的证书。由于 Makecert 命令行已过时,我建议您使用 PowerShell 创建自签名证书,并确保客户端和服务器运行时环境高于 dotnetframwork4.6.2。
https://docs.microsoft.com/en-us/powershell/module/pkiclient/new-selfsignedcertificate?view=win10-ps
https://github.com/dotnet/docs/issues/12000
随时告诉我如果有什么我可以帮忙的。


推荐阅读