Skip to content

Instantly share code, notes, and snippets.

@ghstahl
Created June 20, 2020 18:10
Show Gist options
  • Save ghstahl/146005f2bc4fbe29cff4180b7364b112 to your computer and use it in GitHub Desktop.
Save ghstahl/146005f2bc4fbe29cff4180b7364b112 to your computer and use it in GitHub Desktop.
AzureServiceTokenCredential until https://github.com/Azure/azure-sdk-for-net/issues/8934 gets fixed
using Azure.Security.KeyVault.Keys;
using Azure.Security.KeyVault.Secrets;
using System;
namespace Common
{
public class AzureKeyVaultClients : IAzureKeyVaultClients
{
private AzureKeyVaultTokenCredential _azureKeyVaultTokenCredential;
public AzureKeyVaultClients(AzureKeyVaultTokenCredential azureKeyVaultTokenCredential)
{
_azureKeyVaultTokenCredential = azureKeyVaultTokenCredential;
}
public SecretClient CreateSecretClient(string keyVaultUrl)
{
return new SecretClient(vaultUri: new Uri(keyVaultUrl), credential: _azureKeyVaultTokenCredential);
}
public KeyClient CreateKeyClient(string keyVaultUrl)
{
return new KeyClient(vaultUri: new Uri(keyVaultUrl), credential: _azureKeyVaultTokenCredential);
}
}
}
namespace Common
{
public class AzureKeyVaultTokenCredential : AzureServiceTokenCredential
{
public AzureKeyVaultTokenCredential() : base("https://vault.azure.net")
{
}
}
}
using Azure.Core;
using Microsoft.Azure.Services.AppAuthentication;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Common
{
public class AzureServiceTokenCredential : TokenCredential
{
public AzureServiceTokenCredential(string endPoint)
{
if (string.IsNullOrWhiteSpace(endPoint))
{
throw new ArgumentException("message", nameof(endPoint));
}
EndPoint = endPoint;
}
public string EndPoint { get; }
public override AccessToken GetToken(TokenRequestContext requestContext, CancellationToken cancellationToken)
{
var token = GetTokenAsync(requestContext, cancellationToken).GetAwaiter().GetResult();
return token;
}
public override ValueTask<AccessToken> GetTokenAsync(TokenRequestContext requestContext, CancellationToken cancellationToken)
{
var tokenProvider = new AzureServiceTokenProvider();
return new ValueTask<AccessToken>(tokenProvider
.GetAccessTokenAsync(EndPoint, null, cancellationToken)
.ContinueWith(task => {
return new AccessToken(task.Result, DateTimeOffset.MaxValue);
}));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment