首页 > 解决方案 > 在 C# 中使用 HttpSelfHostServer 验证客户端证书

问题描述

我有一个用 C# 编写的服务,目前可以在 Http 上运行。我想将此迁移到 Https 并希望当某些客户端使用此服务时,应该有一个选项来选择证书以继续,并且只允许一个特定 CA 颁发的证书。

下面是我所做的代码。

HttpSelfHostServer CreateServer(){

   var config = new MySelfHostConfiguration("https://localhost:1234/myService");
   IWebApiApplication application = new SelfHostedApplication(config);    //this is to do some logging and other configuration.
   HttpSelfHostServer selfHost = new HttpSelfHostServer((HttpSelfHostConfiguration)application.HttpConfiguration); //application.HttpConfiguration is same as config

   selfHost.OpenAsync.Wait();

   return selfHost;

}

public class MySelfHostConfiguration : HttpSelfHostConfiguration{

     public MySelfHostConfiguration(string address) : base(address){}
     public MySelfHostConfiguration(Uri address) : base(address){}

     protected override BindingParameterCollection OnConfigureBinding(HttpBinding httpBinding){
         httpBinding.Security.Mode = HttpBindingSecurityMode.Transport;
         httpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate;
         return base.OnConfigureBinding(httpBinding);
     }
}

下面是控制器代码

[Authorize]
public class HelloController : ApiController
{
    public string Get()
    {
        //some code to do stuff
    }
}

我到目前为止所做的是

  1. 使用 netsh 和证书指纹将端口 1234 绑定到证书。

有了这个,我可以浏览到https://localhost:1234/myService(即使它现在不安全,因为我使用了测试证书)。但我也希望当我浏览到 URL 时,我应该被要求选择证书。我想我在需要请求证书和验证 CA 的代码中遗漏了一些东西。有人可以建议缺少什么或需要做什么。

PS:我无法从 HttpSelfHostServer 更改为其他任何内容。

标签: c#asp.net-web-apiself-hostingasp.net-authentication

解决方案


尝试clientcertnegotiation=enable与 netsh 一起使用。我希望这个对你有用


推荐阅读