NumberFour
NumberFour

Reputation: 3611

Obtain TLS client certificate within WCF REST service method

I have a WCF REST service application on .NET 4.7.2. Assume there's a method in the ServiceContract interface:

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

Suppose the IIS running an implementation of this service is configured to accept only HTTPS connections with a client certificate. Also assume the DoSomething() implementation is strictly dependent on the TLS client certificate.

Is there a way I can retrieve this TLS client certificate inside the service implementation?

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

Note: Of course, I could pass the encoded client certificate as parameter to the DoSomething REST call, but then there's no obvious way to match the one being passed to the REST call and the one used to establish the TLS handshake.

Upvotes: 1

Views: 1012

Answers (1)

Popo
Popo

Reputation: 2460

You should be able to get the X509 certificate like this:

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
}

Upvotes: 1

Related Questions