我在.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调用和用于建立REST调用的证书。 TLS握手。
答案 0 :(得分: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
}