Skip to content

Instantly share code, notes, and snippets.

@jwkidd3
Created November 14, 2017 16:39
Show Gist options
  • Save jwkidd3/38ce893c639f11a4f397d6f7094c3689 to your computer and use it in GitHub Desktop.
Save jwkidd3/38ce893c639f11a4f397d6f7094c3689 to your computer and use it in GitHub Desktop.
#in web.config
<!-- ClientId and ClientSecret refer to the web application registration with Azure Active Directory -->
<add key="ClientId" value="clientid" />
<add key="ClientSecret" value="clientsecret" />
<!-- SecretUri is the URI for the secret in Azure Key Vault -->
<add key="SecretUri" value="secreturi" />
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System.Threading.Tasks;
using System.Web.Configuration;
//this is an optional property to hold the secret after it is retrieved
public static string EncryptSecret { get; set; }
//the method that will be provided to the KeyVaultClient
public static async Task<string> GetToken(string authority, string resource, string scope)
{
var authContext = new AuthenticationContext(authority);
ClientCredential clientCred = new ClientCredential(WebConfigurationManager.AppSettings["ClientId"],
WebConfigurationManager.AppSettings["ClientSecret"]);
AuthenticationResult result = await authContext.AcquireTokenAsync(resource, clientCred);
if (result == null)
throw new InvalidOperationException("Failed to obtain the JWT token");
return result.AccessToken;
}
//add these using statements
using Microsoft.Azure.KeyVault;
using System.Web.Configuration;
// I put my GetToken method in a Utils class. Change for wherever you placed your method.
var kv = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(Utils.GetToken));
var sec = await kv.GetSecretAsync(WebConfigurationManager.AppSettings["SecretUri"]);
//I put a variable in a Utils class to hold the secret for general application use.
Utils.EncryptSecret = sec.Value;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment