Search code examples
c#.net-coreasp.net-core-mvcx509certificatecore-api

I get Error when I call get API with certificate


I am working in asp.net core MVC and I call API with certificate and it work perfect in postman and development mode, but when I publish to IIS I get error. (The postman, development and IIS are in the same server)

public async Task<byte[]?> CallApiAsync(string signRequestId)
{

 string ServicePath = @"D:\Service\aa.pfx";

 X509Certificate2 certificate = new(ServicePath, "******");

 // Add the certificate to HttpClientHandler
 var handler = new HttpClientHandler();
 handler.ClientCertificates.Add(certificate);
 handler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;

 // Create HttpClient with HttpClientHandler
 var httpClientWithCert = new HttpClient(handler);

 // Set additional headers
 httpClientWithCert.DefaultRequestHeaders.Add("Language", "EN");
 httpClientWithCert.DefaultRequestHeaders.Add("Authorization", "ApiKey");


 // Define the base URL and parameter
 var baseUrl = "https://url/view";


 // Construct the URL with the parameter
 var fullUrl = $"{baseUrl}?signRequestId={Uri.EscapeDataString(signRequestId)}";

 // Modify the request to GET
 var request = new HttpRequestMessage(HttpMethod.Get, fullUrl);

 // Send the GET request
 var response = await httpClientWithCert.SendAsync(request);
 var contentType = response.Content.Headers.ContentType?.MediaType;

 // Process the response as needed
 if (response.IsSuccessStatusCode && contentType == "multipart/form-data")
 {

     byte[] pdfBytes = await response.Content.ReadAsByteArrayAsync();
     return pdfBytes;
 }
 else
 {
     return null;

 }
}

and I get this error:

An unhandled exception occurred while processing the request. Win32Exception: The credentials supplied to the package were not recognized System.Net.SSPIWrapper.AcquireCredentialsHandle(ISSPIInterface secModule, string package, CredentialUse intent, SCHANNEL_CRED* scc)

AuthenticationException: Authentication failed, see inner exception. System.Net.Security.SslStreamPal.AcquireCredentialsHandle(SslAuthenticationOptions sslAuthenticationOptions, bool newCredentialsRequested)

HttpRequestException: The SSL connection could not be established, see inner exception. System.Net.Http.ConnectHelper.EstablishSslConnectionAsync(SslClientAuthenticationOptions sslOptions, HttpRequestMessage request, bool async, Stream stream, CancellationToken cancellationToken)

I try give permission to folder and I get the same error.


Solution

  • The difference is the identity of the user running the process.

    When it works the code is running in the identity of your user.

    When it does not work it is running in the identity of the IIS application pool.

    Internally the private key is placed in-memory or temporary on-disk certificate store, which lives in the logged on session's user profile. The profile isn't loaded by default for ApplicationPoolIdentity.

    You could try changing the identity of the application pool to Network Service.