title: How to use a client certificate to authenticate and authorize in a Web API
body: <p>I am trying to use a client certificate to authenticate and authorize devices using a Web API and developed a simple proof of concept to work through issues with the potential solution.  I am running into an issue where the client certificate is not being received by the web application.  A number of people of reported this issue, <a href="https://stackoverflow.com/questions/22197762/webapi-httpclient-not-sending-client-certificate">including in this Q&amp;A</a>, but none of them have an answer.  My hope is to provide more detail to revive this issue and hopefully get an answer for my issue.  I am open to other solutions.  The main requirement is that a standalone process written in C# can call a Web API and be authenticated using a client certificate. </p>
  
  <p>The Web API in this POC is very simple and just returns a single value.  It uses an attribute to validate that HTTPS is used and that a client certificate is present.  </p>
  
  <pre><code>public class SecureController : ApiController
  {
      [RequireHttps]
      public string Get(int id)
      {
          return "value";
      }
  
  }
  </code></pre>
  
  <p>Here is the code for the RequireHttpsAttribute:</p>
  
  <pre><code>public class RequireHttpsAttribute : AuthorizationFilterAttribute 
  { 
      public override void OnAuthorization(HttpActionContext actionContext) 
      { 
          if (actionContext.Request.RequestUri.Scheme != Uri.UriSchemeHttps) 
          { 
              actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden) 
              { 
                  ReasonPhrase = "HTTPS Required" 
              }; 
          } 
          else 
          {
              var cert = actionContext.Request.GetClientCertificate();
              if (cert == null)
              {
                  actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden)
                  {
                      ReasonPhrase = "Client Certificate Required"
                  }; 
  
              }
              base.OnAuthorization(actionContext); 
          } 
      } 
  }
  </code></pre>
  
  <p>In this POC I am just checking for the availability of the client certificate.  Once this is working I can add checks for information in the certificate to validate against a list of certificates.</p>
  
  <p>Here are the setting in IIS for SSL for this web application.</p>
  
  <p><a href="https://i.stack.imgur.com/Wr1ZK.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Wr1ZK.png" alt="enter image description here"></a></p>
  
  <p>Here is the code for the client that sends the request with a client certificate.  This is a console application.</p>
  
  <pre><code>    private static async Task SendRequestUsingHttpClient()
      {
          WebRequestHandler handler = new WebRequestHandler();
          X509Certificate certificate = GetCert("ClientCertificate.cer");
          handler.ClientCertificates.Add(certificate);
          handler.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate);
          handler.ClientCertificateOptions = ClientCertificateOption.Manual;
          using (var client = new HttpClient(handler))
          {
              client.BaseAddress = new Uri("https://localhost:44398/");
              client.DefaultRequestHeaders.Accept.Clear();
              client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
  
              HttpResponseMessage response = await client.GetAsync("api/Secure/1");
              if (response.IsSuccessStatusCode)
              {
                  string content = await response.Content.ReadAsStringAsync();
                  Console.WriteLine("Received response: {0}",content);
              }
              else
              {
                  Console.WriteLine("Error, received status code {0}: {1}", response.StatusCode, response.ReasonPhrase);
              }
          }
      }
  
      public static bool ValidateServerCertificate(
        object sender,
        X509Certificate certificate,
        X509Chain chain,
        SslPolicyErrors sslPolicyErrors)
      {
          Console.WriteLine("Validating certificate {0}", certificate.Issuer);
          if (sslPolicyErrors == SslPolicyErrors.None)
              return true;
  
          Console.WriteLine("Certificate error: {0}", sslPolicyErrors);
  
          // Do not allow this client to communicate with unauthenticated servers.
          return false;
      }
  </code></pre>
  
  <p>When I run this test app I get back a status code of 403 Forbidden with a reason phrase of “Client Certificate Required” indicating that it is getting into my RequireHttpsAttribute and it is not finding any client certificates.  Running this through a debugger I have verified that the certificate is getting loaded and added to the WebRequestHandler.  The certificate is exported into a CER file that is being loaded.  The full certificate with the private key is located on the Local Machine’s Personal and Trusted Root stores for the web application server.  For this test the client and web application are being run on the same machine.</p>
  
  <p>I can call this Web API method using Fiddler, attaching the same client certificate, and it works fine.  When using Fiddler it passes the tests in RequireHttpsAttribute and returns a successful status code of 200 and returns the expected value.</p>
  
  <p>Has anybody run into the same issue where HttpClient does not send a client certificate in the request and found a solution?</p>
  
  <p><strong>Update 1:</strong></p>
  
  <p>I also tried getting the certificate from the certificate store that includes the private key.  Here is how I retrieved it:</p>
  
  <pre><code>    private static X509Certificate2 GetCert2(string hostname)
      {
          X509Store myX509Store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
          myX509Store.Open(OpenFlags.ReadWrite);
          X509Certificate2 myCertificate = myX509Store.Certificates.OfType&lt;X509Certificate2&gt;().FirstOrDefault(cert =&gt; cert.GetNameInfo(X509NameType.SimpleName, false) == hostname);
          return myCertificate;
      }
  </code></pre>
  
  <p>I verified that this certificate was getting retrieved correctly and it was being added to the client certificate collection.  But I got the same results where the server code does not retrieve any client certificates.</p>
  
  <p>For completeness here is the code used to retrieve the certificate from a file:</p>
  
  <pre><code>    private static X509Certificate GetCert(string filename)
      {
          X509Certificate Cert = X509Certificate.CreateFromCertFile(filename);
          return Cert;
  
      }
  </code></pre>
  
  <p>You will notice that when you get the certificate from a file it returns an object of type X509Certificate and when you retrieve it from the certificate store it is of type X509Certificate2.  The X509CertificateCollection.Add Method is expecting a type of X509Certificate.</p>
  
  <p><strong>Update 2:</strong>
  I am still trying to figure this out and have tried many different options but to no avail.  </p>
  
  <ul>
  <li>I changed the web application to run on a host name instead of local host.</li>
  <li>I set the web application to require SSL</li>
  <li>I verified that the certificate was set for Client Authentication and that it is in the trusted root</li>
  <li>Besides testing the client certificate in Fiddler I also validated it in Chrome.</li>
  </ul>
  
  <p>At one point during trying these options it started working.  Then I started backing out changes to see what caused it to work. It continued to work.  Then I tried removing the certificate from the trusted root to validate that this was required and it stopped working and now I cannot get it back to working even though I put the certificate back in the trusted root.  Now Chrome will not even prompt me for a certificate like it used too and it fails in Chrome, but still works in Fiddler.  There must be some magic configuration I am missing.</p>
  
  <p>I also tried enabling "Negotiate Client Certificate" in the binding but Chrome still will not prompt me for a client certificate.  Here is the settings using "netsh http show sslcert"</p>
  
  <pre><code> IP:port                 : 0.0.0.0:44398
   Certificate Hash        : 429e090db21e14344aa5d75d25074712f120f65f
   Application ID          : {4dc3e181-e14b-4a21-b022-59fc669b0914}
   Certificate Store Name  : MY
   Verify Client Certificate Revocation    : Disabled
   Verify Revocation Using Cached Client Certificate Only    : Disabled
   Usage Check    : Enabled
   Revocation Freshness Time : 0
   URL Retrieval Timeout   : 0
   Ctl Identifier          : (null)
   Ctl Store Name          : (null)
   DS Mapper Usage    : Disabled
   Negotiate Client Certificate    : Enabled
  </code></pre>
  
  <p>Here is the client certificate I am using:</p>
  
  <p><a href="https://i.stack.imgur.com/ejN8h.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ejN8h.png" alt="enter image description here"></a></p>
  
  <p><a href="https://i.stack.imgur.com/byZZR.png" rel="noreferrer"><img src="https://i.stack.imgur.com/byZZR.png" alt="enter image description here"></a></p>
  
  <p><a href="https://i.stack.imgur.com/lMMaF.png" rel="noreferrer"><img src="https://i.stack.imgur.com/lMMaF.png" alt="enter image description here"></a></p>
  
  <p>I am baffled as to what the issue is.  I am adding a bounty for anyone that can help me figure this out.</p>