'The SSL connection could not be established in case of proxy [The remote certificate is invalid according to the validation procedure]
I have a WebAPI project built on .Net Core 3.1 and deployed on Azure App Service. When a request comes with specific URL, I am creating a proxy and redirect it to a third party service URL using
app.Map("/api/xxx/queries", builder =>
{
builder.RunProxy<ProxyMiddleware>();
});
in Startp.cs file.
The URL to which I am redirecting the request, has public SSL certificate installed on their side. I have written code to add certificate while forwarding request but still I get above error while trying to access third party service. I have uploaded issued certificate (.CER) on Azure App Service and accessing it through the thumbprint.
Please refer below code for more information.
Startup.cs
public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.AddProxy(config => config.ConfigurePrimaryHttpMessageHandler(CreatePrimaryHandler));
services.AddCertificateForwarding(options =>
{
options.CertificateHeader = "X-SSL-CERT";
options.HeaderConverter = headerValue =>
{
X509Certificate2 clientCertificate = null;
if (!string.IsNullOrWhiteSpace(headerValue))
{
clientCertificate = new X509Certificate2(GetCertificate(_hipApiCertificateThumbprint));
}
return clientCertificate!;
};
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseCertificateForwarding();
app.UseAuthentication();
app.Map("/api/xxx/queries", builder =>
{
builder.RunProxy<ProxyMiddleware>();
});
}
private HttpMessageHandler CreatePrimaryHandler()
{
var clientHandler = new HttpClientHandler();
var certficate = GetCertificate("certificateThumbprint");
if (certficate != null)
{
clientHandler.ClientCertificates.Add(certficate);
clientHandler.ClientCertificateOptions = ClientCertificateOption.Manual;
}
return clientHandler;
}
private static X509Certificate2 GetCertificate(string certThumbprint)
{
using (X509Store certStore = new X509Store(StoreName.My, StoreLocation.CurrentUser))
{
certStore.Open(OpenFlags.ReadOnly);
var certCollection = certStore.Certificates.Find(X509FindType.FindByThumbprint, certThumbprint, false);
return certCollection.OfType<X509Certificate2>().FirstOrDefault();
}
}
ProxyMiddleware.cs
public sealed class ProxyMiddleware : IProxyHandler
{
private readonly string _thirdPartyServiceUrl;
public ProxyMiddleware()
{
_thirdPartyServiceUrl = "xxx.yyyyyyyy.zzz/abc"
}
public async Task<HttpResponseMessage> HandleProxyRequest(HttpContext context)
{
var forwardContext = context.ForwardTo(_thirdPartyServiceUrl);
forwardContext.AddXForwardedHeaders();
return await forwardContext.Send();
}
}
Note: I tried making the same request through POSTMAN and it is working fine so there is no issue with certificate validation.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
