Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible in a .NET Core application to retrieve a certificate from AWS Certificate Manager and use it in a HttpClient post?

My .Net core application makes a post request to an external web service using HttpClient. The external web service requires a certificate to validate against.

The certificates are installed in AWS and I have an ARN that points to the certificate.

Is it possible to get the certificate programitically from AWS Certificate Manager and use this in my HtppClient, for example this is the code I would use normally to add a certificate but I need to get it from AWS.

   private HttpClientHandler HttpClientHandler()
   {
        var handler = new HttpClientHandler
        {
            ClientCertificateOptions = ClientCertificateOption.Manual,
            SslProtocols = SslProtocols.Tls12
        };
        handler.ClientCertificates.Add(new X509Certificate2("cert.crt")); //TODO: fetch from AWS.
        return handler;
    }
like image 992
WooHoo Avatar asked Dec 17 '22 21:12

WooHoo


1 Answers

So, it's possible.

I installed AWSSDK.Core and AWSSDK.CertificateManager from NuGet.

Then, I created a credentials file for AWS, see instructions from Amazon https://docs.aws.amazon.com/cli/latest/userguide/cli-config-files.html

Next, I used the AmazonCertificateManagerClient to get the certificate.

AmazonCertificateManagerClient client = new AmazonCertificateManagerClient();
var certificates = client.GetCertificateAsync(arn).Result;

I then converted the certificate from string to bytes and then add to the handler.

var handler = new HttpClientHandler{
  ClientCertificateOptions = ClientCertificateOption.Manual,
  SslProtocols = SslProtocols.Tls12
};

byte[] toBytes = Encoding.ASCII.GetBytes(certificates.Certificate);
var cert = new X509Certificate2(toBytes);

handler.ClientCertificates.Add(cert); 
var httpClient = new HttpClient(handler);

Obviously, not production worthy code, hope it helps.

like image 61
WooHoo Avatar answered May 01 '23 10:05

WooHoo