Skip to content

Instantly share code, notes, and snippets.

@benhysell
Created July 23, 2018 13:06
Show Gist options
  • Save benhysell/43bd1c4b161712f03867f45aafa3332a to your computer and use it in GitHub Desktop.
Save benhysell/43bd1c4b161712f03867f45aafa3332a to your computer and use it in GitHub Desktop.
Client to call Azure for signing keys for SPA with oidc-client
using Newtonsoft.Json;
namespace Web.DataTransferObjects.Utilities
{
/// <summary>
/// Azure signing key structure
/// </summary>
public class AzureSigningKey
{
/// <summary>
///
/// </summary>
public string Kty { get; set; }
/// <summary>
///
/// </summary>
public string Use { get; set; }
/// <summary>
///
/// </summary>
public string Kid { get; set; }
/// <summary>
///
/// </summary>
public string X5T { get; set; }
/// <summary>
///
/// </summary>
public string N { get; set; }
/// <summary>
///
/// </summary>
public string E { get; set; }
/// <summary>
///
/// </summary>
public string[] X5C { get; set; }
}
/// <summary>
/// Full Azure Key
/// </summary>
public class AzureKey
{
/// <summary>
/// Keys
/// </summary>
[JsonProperty("keys")]
public AzureSigningKey[] AzureSigningKeys { get; set; }
}
}
using System;
using System.Net.Http;
using System.Threading.Tasks;
using DataTransferObjects.Utilities;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
namespace Web.Utilities
{
/// <summary>
/// Client to call Azure for Signing Keys for spa
/// </summary>
public class SigningKeysClient
{
private HttpClient _client;
private ILogger<SigningKeysClient> _logger;
/// <summary>
/// Signing keys client
/// </summary>
/// <param name="client"></param>
/// <param name="logger"></param>
/// <param name="config"></param>
public SigningKeysClient(HttpClient client, ILogger<SigningKeysClient> logger, IConfiguration config)
{
_client = client;
_client.BaseAddress = new Uri($"https://login.microsoftonline.com");
_logger = logger;
}
/// <summary>
/// Query azure for latest signing keys
/// </summary>
/// <returns></returns>
public async Task<AzureKey> GetSigningKeysAsync()
{
try
{
var keysUrl = new Uri($"/common/discovery/keys", UriKind.Relative);
_logger.LogWarning($"HttpClient: Loading {keysUrl}");
var res = await _client.GetAsync(keysUrl);
res.EnsureSuccessStatusCode();
var retrunValue = await res.Content.ReadAsAsync<AzureKey>();
return retrunValue;
}
catch (HttpRequestException ex)
{
_logger.LogError($"An error occurred connecting to jwks URI API {ex.ToString()}");
throw;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment