我在 .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/