c# - 在 WCF REST 服务方法中获取 TLS 客户端证书

标签 c# .net wcf ssl iis

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

[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 握手。

最佳答案

您应该能够像这样获得 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
}

关于c# - 在 WCF REST 服务方法中获取 TLS 客户端证书,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53667313/

相关文章:

c# - 从 HashSet 中获取 X 个最旧的项目?

c# - 在带有身份验证的 MonoTouch 中使用 WCF 服务

wcf - 消费服务: The type name ‘AAA' does not exist in the type ‘YYY.YYY’ 时出错

c# - 未插入 NULL 值

c# - 如何使用属性调用类上的方法?

C# 按钮仅在第二次单击时触发

wcf - WCF NetTCPBinding 中的二进制序列化

c# - 净::ERR_CONNECTION_RESET REST WCF

c# - LINQ 加入具有 NULL 元素的多个数据集

c# - 是否已添加事件处理程序?