SSL Certificate authentication in ASP.NET Core
Microsoft.AspNetCore.Authentication.Certificate
contains an implementation similar to Certificate Authentication for ASP.NET
Core. Certificate authentication happens at the TLS level, long before it ever
gets to ASP.NET Core. More accurately, this is an authentication handler that
validates the certificate and then gives you an event where you can resolve
that certificate to a ClaimsPrincipal.
Implement an HttpClient using a certificate and IHttpClientFactory
In the following example, a client certificate is added to a HttpClientHandler using the ClientCertificates property from the handler. This handler can then be
used in a named instance of an HttpClient using the ConfigurePrimaryHttpMessageHandler method. This is setup in Program.cs:
var clientCertificate =
new X509Certificate2(
Path.Combine(_environment.ContentRootPath, "mysample_cert.pfx"), "12345678");
builder.Services.AddHttpClient("namedClient", c
=>
{
}).ConfigurePrimaryHttpMessageHandler(() =>
{
var
handler = new HttpClientHandler();
handler.ClientCertificates.Add(clientCertificate);
return
handler;
});
The IHttpClientFactory
can then be used to get the named instance
with the handler and the certificate. The CreateClient
method with the name of the client defined
in Program.cs
is used to get the instance. The HTTP request can be
sent using the client as required:
public class SampleHttpService
{
private readonly
IHttpClientFactory _httpClientFactory;
public SampleHttpService(IHttpClientFactory
httpClientFactory)
=> _httpClientFactory = httpClientFactory;
public async
Task<JsonDocument> GetAsync()
{
var
httpClient = _httpClientFactory.CreateClient("namedClient");
var
httpResponseMessage = await httpClient.GetAsync("https://sample.com");
if
(httpResponseMessage.IsSuccessStatusCode)
{
return
JsonDocument.Parse(
await
httpResponseMessage.Content.ReadAsStringAsync());
}
throw new
ApplicationException($"Status code: {httpResponseMessage.StatusCode}");
}
}
If the correct certificate is sent to the server, the data is returned. If no certificate or the wrong certificate is sent, an HTTP 403 status code is returned.
Comments
Post a Comment