Skip to content

Instantly share code, notes, and snippets.

@AsishP
Created October 3, 2018 10:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AsishP/671872b7cb86698143707d2fb0d3160f to your computer and use it in GitHub Desktop.
Save AsishP/671872b7cb86698143707d2fb0d3160f to your computer and use it in GitHub Desktop.
public SecureString GetSecret()
{
try
{
// Get the Secret Uri from Key Vault
string SecretUri = System.Environment.GetEnvironmentVariable("<KeyValutSecretUri>");
var kvToken = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(GetToken));
var kvSecret = kvToken.GetSecretAsync(SecretUri).Result;
SecureString secpass = new SecureString();
foreach (char charpass in kvSecret.Value)
{
secpass.AppendChar(charpass);
}
return secpass;
}
catch (Exception ex)
{
throw ex;
}
}
public async Task<string> GetToken(string authority, string resource, string scope)
{
AuthenticationResult authResult = null;
try
{
string ClientId = System.Environment.GetEnvironmentVariable("ClientId");
string ClientSecret = System.Environment.GetEnvironmentVariable("ClientSecret");
var authContext = new AuthenticationContext(authority);
ClientCredential clientCred = new ClientCredential(ClientId, ClientSecret);
Task authTask = Task.Run(async () => authResult = await authContext.AcquireTokenAsync(resource, clientCred));
authTask.Wait();
}
catch (Exception ex)
{
throw new Exception($"Function Error at Token Retrieval: {ex.Message}");
}
if (authResult == null)
throw new InvalidOperationException("Failed to obtain the JWT token");
return authResult.AccessToken;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment