Helper class to store service principal keys and retrieve them from the Windows Credential Store.
        /// <summary>
        /// Authenticate using the secret for the specified client from the key store
        /// </summary>
        /// <param name="clientId">The active directory client id for the application.</param>
        /// <param name="audience">The intended audience for authentication</param>
        /// <param name="context">The AD AuthenticationContext to use</param>
        /// <returns></returns>
        public async Task <AuthenticationResult> AuthenticateAsync(string clientId, string audience, AuthenticationContext context)
        {
            var task = new Task <SecureString>(() =>
            {
                return(ServicePrincipalKeyStore.GetKey(clientId, _tenantId));
            });

            task.Start();
            var key = await task.ConfigureAwait(false);

            return(await context.AcquireTokenAsync(audience, new ClientCredential(clientId, key)));
        }
 private void StoreAppKey(string appId, string tenantId, SecureString appKey)
 {
     ServicePrincipalKeyStore.SaveKey(appId, tenantId, appKey);
 }
 private SecureString LoadAppKey(string appId, string tenantId)
 {
     return(ServicePrincipalKeyStore.GetKey(appId, tenantId));
 }