'Consume SSL Secured APIs in ASP.NET Core 6 MVC Client
We have an application that has two projects as follows (1) AppClient – This dotnet core MVC project and it is running on WebServer on IIS (2) AppService – this is dotnet core WebAPI project. It runs on AppServer on IIS.
Only AppClient can consume APIs exposed by AppService. These APIs are hosted over HTTP. Currently both applications are over the same network. We have a requirement to secure REST APIs by using HTTPS. I have a few questions:
If WebAPIs are hosted over HTTPS using SSL, what code changes will I have to do on AppClient? Will I have to write a cryptography layer in order to every time send encrypted requests to AppService or IIS will take care of it? If so, how and where I am supposed to maintain the public keys served by AppService.
Do I have to make any code change in AppService to host it over HTTPS or binding it with SSL in IIS is all that I need to do?
Solution 1:[1]
To consume APIs hosted on HTTPS, an instance of HttpClientHandler needs to be created and then it should be passed as an argument to HttpClient. See the code below
HttpClientHandler httpClientHandler = new HttpClientHandler();
httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, sslPolicyErrors) =>
{
if (sslPolicyErrors == SslPolicyErrors.None && cert.GetCertHashString().ToLower() == "certificateThumbPrint")
{
return true; //Is valid
}
return false;
};
client = new HttpClient(httpClientHandler);
client.BaseAddress = new Uri("...");
client.Timeout = TimeSpan.FromSeconds(...);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |