繁体   English   中英

在 C# 中使用 HttpSelfHostServer 验证客户端证书

[英]Authenticate client certificate using HttpSelfHostServer in C#

我有一个用 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 更改为其他任何内容。

尝试在 netsh 中使用clientcertnegotiation=enable 我希望这个对你有用

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM