无法获取证书消息凭据以在我的 WCF 服务中工作

Can't get certificate message credentials to work in my WCF service

我制作了一个托管 WCF 服务的控制台应用程序。我现在正在尝试修改它。这是目前有效的...

Program.cs:

namespace FileRetrievalPoC
{
    class Program
    {
        static void Main(string[] args)
        {
            var address = "https://localhost:8000/FileRetrievalPoC";
            Console.WriteLine("Starting a service at {0}...", address);
            FileRetrievalService.Start(address, StoreLocation.LocalMachine, StoreName.TrustedPeople, "b7ba8f6e4c33ba55053f2e85898b383e40bf8ac9");
            Console.WriteLine("Service started.");
            Console.WriteLine("Press Enter to create a new proxy client and call the Get method.");
            Console.WriteLine("Press Escape to end the application.");
            while (true)
            {
                var key = Console.ReadKey();
                if (key.Key == ConsoleKey.Enter)
                {
                    var proxy = FileRetrievalService.Connect(address, "localhost", "username", "password");
                    Console.WriteLine("Read the following from the server: {0}", proxy.Get(@"C:\Users\User\Desktop\Document.txt"));
                    FileRetrievalService.CloseClients();
                }
                else if (key.Key == ConsoleKey.Escape)
                    break;
            }
            FileRetrievalService.CloseServer();
        }
    }
}

FileRetrievalService.cs:

class FileRetrievalService : IFileRetrieval
{

    private static BasicHttpsBinding _binding = new BasicHttpsBinding()
    {
        HostNameComparisonMode = HostNameComparisonMode.Exact,
        Security = new BasicHttpsSecurity()
        {
            Message = new BasicHttpMessageSecurity()
            {
                AlgorithmSuite = SecurityAlgorithmSuite.Basic256Sha256Rsa15,
                ClientCredentialType = BasicHttpMessageCredentialType.UserName
            },
            Mode = BasicHttpsSecurityMode.TransportWithMessageCredential,
            Transport = new HttpTransportSecurity()
            {
                ClientCredentialType = HttpClientCredentialType.Windows,
            }
        }
    };
    private static ChannelFactory<IFileRetrieval> _channelFactory;
    private static ServiceHost _host;

    public static void Start(string address, StoreLocation location, StoreName name, string thumbprint)
    {
        _host = new ServiceHost(typeof(FileRetrievalService));
        _host.Credentials.ServiceCertificate.SetCertificate(location, name, X509FindType.FindByThumbprint, thumbprint);
        _host.AddServiceEndpoint(typeof(IFileRetrieval), _binding, address);
        _host.Open();
    }

    public static void CloseClients()
    {
        if (_channelFactory != null)
            _channelFactory.Close();
        _channelFactory = null;
    }

    public static void CloseServer()
    {
        if (_host != null)
            _host.Close();
        _host = null;
    }

    public static void CloseServerAndClients()
    {
        CloseServer();
        CloseClients();
    }

    public static IFileRetrieval Connect(string address, string domain, string username, string password)
    {
        if (_channelFactory == null)
        {
            _channelFactory = new ChannelFactory<IFileRetrieval>(_binding, address);
            _channelFactory.Credentials.UserName.UserName = domain + '\' + username;
            _channelFactory.Credentials.UserName.Password = password;
            _channelFactory.Credentials.Windows.ClientCredential = new NetworkCredential(username, password, domain);
        }
        return _channelFactory.CreateChannel();
    }

    public string Get(string path)
    {
        return File.ReadAllText(path);
    }

    public void Set(string path, string contents)
    {
        File.WriteAllText(path, contents);
    }
}

IFileRetrieval.cs:

[ServiceContract]
public interface IFileRetrieval
{
    [OperationContract]
    string Get(string path);
    [OperationContract]
    void Set(string path, string contents);
}

以上所有代码都有效,因为:

  1. Server-side 在绑定上有 ClientCredentialType = BasicHttpMessageCredentialType.UserName
  2. Client-side 在 _channelFactory.Credentials.UserName object 上设置用户名凭据。

我想增加安全性,并让 client-side 在连接到服务器时也提供 SSL 证书。为了尝试做到这一点,我使用以下逻辑在第 1 点和第 2 点的代码中进行了以下替换:

  1. 我正在尝试在绑定上使用 ClientCredentialType = BasicHttpMessageCredentialType.Certificate 而不是 ClientCredentialType = BasicHttpMessageCredentialType.UserName
  2. Connect方法中,我现在设置客户端的证书(_channelFactory.Credentials.ClientCertificate.SetCertificate(location, name, X509FindType.FindByThumbprint, thumbprint);)和修改方法以获取适当的证书信息(StoreLocation location, StoreName name, string thumbprint)传入完全相同要引用的参数,来自 client-side,来自 server-side 的同一证书。我删除了之前设置 _channelFactory.Credentials.UserName object.
  3. 的逻辑

这没有用,我得到以下异常:

An unsecured or incorrectly secured fault was received from the other party. See the inner FaultException for the fault code and detail.

它的内部异常说:

An error occurred when verifying security for the message.

从这里去哪里?我没有使用 IIS,那么如何进一步跟踪此错误?我有点不知所措。我希望有人能解释可能出了什么问题,以及我可以做些什么来修复错误或进一步调试它。

编辑:我想出了一个进一步调试它的方法,但它并没有比我想象的更有帮助。在我的 App.config 中,我添加了以下跟踪:

<system.diagnostics>
  <sources>
    <source name="System.ServiceModel" switchValue="Verbose, ActivityTracing" propagateActivity="true">
      <listeners>
        <add name="listener" type="System.Diagnostics.XmlWriterTraceListener" initializeData= "C:\Users\YourAccountUsername\Desktop\WCFTraces.svclog" />
      </listeners>
    </source>
    <source name="System.ServiceModel.MessageLogging" switchValue="Verbose, ActivityTracing" propagateActivity="true">
      <listeners>
        <add name="listener" type="System.Diagnostics.XmlWriterTraceListener" initializeData= "C:\Users\YourAccountUsername\Desktop\WCFTraces.svclog" />
      </listeners>
    </source>
  </sources>
</system.diagnostics>

现在在 WCFTraces.svclog 中,我也看到了服务器端的一堆异常。第一个是:

Security processor was unable to find a security header in the message. This might be because the message is an unsecured fault or because there is a binding mismatch between the communicating parties. This can occur if the service is configured for security and the client is not using security.

考虑到我已经指定了客户端证书,我不确定为什么邮件没有安全性 header。缺少什么客户端代码?

编辑:啊,我也看到了这个错误:

The key size requirements for the 'Basic256Sha256Rsa15' algorithm suite are not met by the 'System.IdentityModel.Tokens.X509SecurityToken' token which has key size of '8192'.

它低于接收字节数。我的证书有一个 8192 字节的私有密钥和 public 密钥,但这与我选择的 AlgorithmSuite = SecurityAlgorithmSuite.Basic256Sha256Rsa15 一定不匹配。有谁知道我应该在这里做什么来允许这个证书?我可以尝试为此使用 256 位密钥...或者我的证书上的签名算法是 512 位的问题?

我终于明白了。这些错误误导我走上了一条黑暗的道路,但现在我明白了。

问题

这似乎是不成文的规定。当您指定 Mode = BasicHttpsSecurityMode.TransportWithMessageCredential 告诉它同时使用消息和传输凭据,然后您使用证书作为消息凭据时,

Message = new BasicHttpMessageSecurity()
{
    AlgorithmSuite = SecurityAlgorithmSuite.Basic256Sha256Rsa15,
    ClientCredentialType = BasicHttpMessageCredentialType.Certificate
}

如果密钥超过 4096 位,则不能将证书用作您的消息凭据。

解决方案

我使用 SHA 512 作为签名算法,使用 4096 位 RSA 密钥对制作了一个新的自签名证书。