Skip to content

Commit

Permalink
add http client handler with x509 (#1469)
Browse files Browse the repository at this point in the history
  • Loading branch information
dpvreony committed Sep 4, 2023
1 parent 03b0e56 commit 8e26df7
Show file tree
Hide file tree
Showing 3 changed files with 74 additions and 1 deletion.
@@ -0,0 +1,37 @@
// Copyright (c) 2022 DHGMS Solutions and Contributors. All rights reserved.
// This file is licensed to you under the MIT license.
// See the LICENSE file in the project root for full license information.

using System;
using System.Security.Cryptography.X509Certificates;

namespace Whipstaff.Runtime.Cryptography.X509
{
/// <summary>
/// Extension methods for <see cref="X509Certificate2"/>.
/// </summary>
public static class X509Certificate2Extensions
{
/// <summary>
/// Check to ensure that the certificate has a private key.
/// </summary>
/// <param name="certificate">Certificate to check.</param>
public static void EnsurePrivateKey(this X509Certificate2 certificate)
{
try
{
// we wrap in try block as HasPrivateKey throws an exception on certain runtimes.
if (certificate.HasPrivateKey)
{
return;
}
}
catch
{
// no op
}

throw new ArgumentException("Certificate does not have a private key", nameof(certificate));
}
}
}
Expand Up @@ -5,7 +5,6 @@
using System;
using System.Collections.Generic;
using System.Security.Cryptography.X509Certificates;
using System.Text;

namespace Whipstaff.Runtime.Cryptography.X509
{
Expand Down
37 changes: 37 additions & 0 deletions src/Whipstaff.Runtime/Http/HttpClientHandlerFactory.cs
@@ -0,0 +1,37 @@
// Copyright (c) 2022 DHGMS Solutions and Contributors. All rights reserved.
// This file is licensed to you under the MIT license.
// See the LICENSE file in the project root for full license information.

using System;
using System.Net.Http;
using System.Security.Cryptography.X509Certificates;
using Whipstaff.Runtime.Cryptography.X509;

namespace Whipstaff.Runtime.Http
{
/// <summary>
/// Factory for creating <see cref="HttpClientHandler"/> instances.
/// </summary>
public static class HttpClientHandlerFactory
{
/// <summary>
/// Creates a Http Client Handler with a client certificate attached.
/// </summary>
/// <param name="certificate">Certificate to bind as client certificate.</param>
/// <returns>&lt;see cref="HttpClientHandler"/&gt; instance.</returns>
public static HttpClientHandler GetHttpClientHandlerWithClientCertificate(X509Certificate2 certificate)
{
if (certificate == null)
{
throw new ArgumentNullException(nameof(certificate));
}

certificate.EnsurePrivateKey();

var clientHandler = new HttpClientHandler();
_ = clientHandler.ClientCertificates.Add(certificate);

return clientHandler;
}
}
}

0 comments on commit 8e26df7

Please sign in to comment.