【问题标题】:Obtain TLS client certificate within WCF REST service method在 WCF REST 服务方法中获取 TLS 客户端证书
【发布时间】:2018-12-07 10:07:39
【问题描述】:

我在 .NET 4.7.2 上有一个 WCF REST 服务应用程序。假设ServiceContract接口中有一个方法:

[ServiceContract]
public interface MyService
{
    [OperationContract]
    [WebGet(UriTemplate = "DoSomething", ResponseFormat = WebMessageFormat.Json)]
    ResponseDto DoSomething();
}

假设运行此服务实现的 IIS 配置为仅接受带有客户端证书的 HTTPS 连接。还假设 DoSomething() 实现严格依赖于 TLS 客户端证书。

有没有办法可以在服务实现中检索此 TLS 客户端证书?

public class MyServiceImpl : MyService
{
    public ResponseDto DoSomething()
    {
        // Something like GetClientCertFromTlsSession() 
        // to get the X509Certificate2 instance?
    }
}

注意:当然,我可以将编码的客户端证书作为参数传递给DoSomething REST 调用,但是没有明显的方法来匹配传递给 REST 调用的证书和用于建立 TLS 握手的证书.

【问题讨论】:

  • 只是因为我的无知;但是为什么要发送客户端证书?
  • 我需要对服务进行相互验证的 TLS 通道。此外,服务需要知道客户端证书才能正常工作。
  • 我假设您在绑定配置中配置客户端证书?
  • This question 似乎有几个答案概述了不同的可能方法。
  • @NumberFour:谢谢,我不知道需要发送实际的证书。我总是假设(哎呀)带有客户端请求签名的消息就足够了。

标签: c# .net wcf ssl iis


【解决方案1】:

您应该可以像这样获得 X509 证书:

X509Certificate2 cert = null;
try
{
    if (OperationContext.Current.ServiceSecurityContext.AuthorizationContext.ClaimSets.Count > 0)
    {
        cert = ((X509CertificateClaimSet)OperationContext.Current.ServiceSecurityContext.AuthorizationContext.ClaimSets[0]).X509Certificate;
    }
    else
    {
        throw new Exception("missing cert...");
    }
}
catch (Exception ex)
{
    //log something and handle exception
}

【讨论】:

  • 是否有文档提到证书在 ClaimSets 的索引 0 处可用?
  • 不,在这种情况下只有一个证书,所以它正在获取第一个证书,这可能是大多数情况下的情况,如果它们是更多的证书,您需要添加额外的逻辑找到所需的证书。
猜你喜欢
  • 1970-01-01
  • 2019-05-02
  • 1970-01-01
  • 1970-01-01
  • 2015-09-27
  • 1970-01-01
  • 1970-01-01
  • 2020-08-05
  • 1970-01-01
相关资源
最近更新 更多