public async Task Identity_ClientSideUserAuthentication_DisableAutomaticAuthentication() { #region Snippet:Identity_ClientSideUserAuthentication_DisableAutomaticAuthentication var credential = new InteractiveBrowserCredential(new InteractiveBrowserCredentialOptions { DisableAutomaticAuthentication = true }); await credential.AuthenticateAsync(); var client = new SecretClient(new Uri("https://myvault.azure.vaults.net/"), credential); #endregion #region Snippet:Identity_ClientSideUserAuthentication_DisableAutomaticAuthentication_ExHandling try { client.GetSecret("secret"); } catch (AuthenticationRequiredException e) { await EnsureAnimationCompleteAsync(); await credential.AuthenticateAsync(e.TokenRequestContext); client.GetSecret("secret"); } #endregion }
public static async Task Main() { InteractiveBrowserCredential credential; if (!File.Exists(AUTH_RECORD_PATH)) { credential = new InteractiveBrowserCredential(new InteractiveBrowserCredentialOptions { TokenCache = new PersistentTokenCache() }); AuthenticationRecord authRecord = await credential.AuthenticateAsync(); using var authRecordStream = new FileStream(AUTH_RECORD_PATH, FileMode.Create, FileAccess.Write); await authRecord.SerializeAsync(authRecordStream); await authRecordStream.FlushAsync(); } else { using var authRecordStream = new FileStream(AUTH_RECORD_PATH, FileMode.Open, FileAccess.Read); AuthenticationRecord authRecord = await AuthenticationRecord.DeserializeAsync(authRecordStream); credential = new InteractiveBrowserCredential(new InteractiveBrowserCredentialOptions { TokenCache = new PersistentTokenCache(), AuthenticationRecord = authRecord }); } var client = new SecretClient(new Uri("https://myvault.azure.vaults.net/"), credential); }
public override Task <IAccessToken> Authenticate(AuthenticationParameters parameters, CancellationToken cancellationToken) { var interactiveParameters = parameters as InteractiveParameters; var onPremise = interactiveParameters.Environment.OnPremise; //null instead of "organizations" should be passed to Azure.Identity to support MSA account var tenantId = onPremise ? AdfsTenant : (string.Equals(parameters.TenantId, OrganizationsTenant, StringComparison.OrdinalIgnoreCase) ? null : parameters.TenantId); var tokenCacheProvider = interactiveParameters.TokenCacheProvider; var resource = interactiveParameters.Environment.GetEndpoint(interactiveParameters.ResourceId) ?? interactiveParameters.ResourceId; var scopes = AuthenticationHelpers.GetScope(onPremise, resource); var clientId = AuthenticationHelpers.PowerShellClientId; var requestContext = new TokenRequestContext(scopes); var authority = interactiveParameters.Environment.ActiveDirectoryAuthority; var options = new InteractiveBrowserCredentialOptions() { ClientId = clientId, TenantId = tenantId, TokenCachePersistenceOptions = tokenCacheProvider.GetTokenCachePersistenceOptions(), AuthorityHost = new Uri(authority), RedirectUri = GetReplyUrl(onPremise, interactiveParameters), }; var browserCredential = new InteractiveBrowserCredential(options); TracingAdapter.Information($"{DateTime.Now:T} - [InteractiveUserAuthenticator] Calling InteractiveBrowserCredential.AuthenticateAsync with TenantId:'{options.TenantId}', Scopes:'{string.Join(",", scopes)}', AuthorityHost:'{options.AuthorityHost}', RedirectUri:'{options.RedirectUri}'"); var authTask = browserCredential.AuthenticateAsync(requestContext, cancellationToken); return(MsalAccessToken.GetAccessTokenAsync( authTask, browserCredential, requestContext, cancellationToken)); }
public override Task <IAccessToken> Authenticate(AuthenticationParameters parameters, CancellationToken cancellationToken) { var interactiveParameters = parameters as InteractiveParameters; var onPremise = interactiveParameters.Environment.OnPremise; //null instead of "organizations" should be passed to Azure.Identity to support MSA account var tenantId = onPremise ? AdfsTenant : (string.Equals(parameters.TenantId, OrganizationsTenant, StringComparison.OrdinalIgnoreCase) ? null : parameters.TenantId); var tokenCacheProvider = interactiveParameters.TokenCacheProvider; var resource = interactiveParameters.Environment.GetEndpoint(interactiveParameters.ResourceId) ?? interactiveParameters.ResourceId; var scopes = AuthenticationHelpers.GetScope(onPremise, resource); var clientId = AuthenticationHelpers.PowerShellClientId; var requestContext = new TokenRequestContext(scopes); var authority = interactiveParameters.Environment.ActiveDirectoryAuthority; AzureSession.Instance.TryGetComponent(nameof(PowerShellTokenCache), out PowerShellTokenCache tokenCache); var options = new InteractiveBrowserCredentialOptions() { ClientId = clientId, TenantId = tenantId, TokenCache = tokenCache.TokenCache, AuthorityHost = new Uri(authority), RedirectUri = GetReplyUrl(onPremise, interactiveParameters), }; var browserCredential = new InteractiveBrowserCredential(options); var authTask = browserCredential.AuthenticateAsync(requestContext, cancellationToken); return(MsalAccessToken.GetAccessTokenAsync( authTask, browserCredential, requestContext, cancellationToken)); }
private async Task <TokenCredential> GetCredentialAsyncImpl() { string authRecordPath = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "dotnet-eng", "auth-data.json" ); // Fetch the cached auth record, so that we don't have to browser auth every time the user uses the tool AuthenticationRecord record = null; if (File.Exists(authRecordPath)) { try { await using FileStream stream = File.Open(authRecordPath, FileMode.Open, FileAccess.Read, FileShare.Read); record = await AuthenticationRecord.DeserializeAsync(stream); } catch { // Failed to cache, next attempt will just re-prompt } } var cred = new InteractiveBrowserCredential( new InteractiveBrowserCredentialOptions { TokenCache = new PersistentTokenCache(false), AuthenticationRecord = record, } ); if (record == null) { // If we didn't already have a record, call authenticate async to trigger the browser login // so we can get the authentication record and store it record = await cred.AuthenticateAsync(); try { Directory.CreateDirectory(Path.GetDirectoryName(authRecordPath)); await using FileStream stream = File.Create(authRecordPath); await record.SerializeAsync(stream); } catch { // Failed to cache, next attempt will just re-prompt } } _userId = record.Username; return(cred); }
public async Task AuthenticateFollowedByGetTokenAsync() { var cred = new InteractiveBrowserCredential(); // this should pop browser await cred.AuthenticateAsync(); // this should not pop browser AccessToken token = await cred.GetTokenAsync(new TokenRequestContext(new string[] { "https://vault.azure.net/.default" })).ConfigureAwait(false); Assert.NotNull(token.Token); }
public static async Task Main() { #region Snippet:AuthenticationRecord_TokenCachePersistenceOptions const string TOKEN_CACHE_NAME = "MyTokenCache"; InteractiveBrowserCredential credential; AuthenticationRecord authRecord; // Check if an AuthenticationRecord exists on disk. // If it does not exist, get one and serialize it to disk. // If it does exist, load it from disk and deserialize it. if (!File.Exists(AUTH_RECORD_PATH)) { // Construct a credential with TokenCachePersistenceOptions specified to ensure that the token cache is persisted to disk. // We can also optionally specify a name for the cache to avoid having it cleared by other applications. credential = new InteractiveBrowserCredential( new InteractiveBrowserCredentialOptions { TokenCachePersistenceOptions = new TokenCachePersistenceOptions { Name = TOKEN_CACHE_NAME } }); // Call AuthenticateAsync to fetch a new AuthenticationRecord. authRecord = await credential.AuthenticateAsync(); // Serialize the AuthenticationRecord to disk so that it can be re-used across executions of this initialization code. using var authRecordStream = new FileStream(AUTH_RECORD_PATH, FileMode.Create, FileAccess.Write); await authRecord.SerializeAsync(authRecordStream); } else { // Load the previously serialized AuthenticationRecord from disk and deserialize it. using var authRecordStream = new FileStream(AUTH_RECORD_PATH, FileMode.Open, FileAccess.Read); authRecord = await AuthenticationRecord.DeserializeAsync(authRecordStream); // Construct a new client with our TokenCachePersistenceOptions with the addition of the AuthenticationRecord property. // This tells the credential to use the same token cache in addition to which account to try and fetch from cache when GetToken is called. credential = new InteractiveBrowserCredential( new InteractiveBrowserCredentialOptions { TokenCachePersistenceOptions = new TokenCachePersistenceOptions { Name = TOKEN_CACHE_NAME }, AuthenticationRecord = authRecord }); } // Construct our client with the credential which is connected to the token cache // with the capability of silent authentication for the account specified in the AuthenticationRecord. var client = new SecretClient(new Uri("https://myvault.vault.azure.net/"), credential); #endregion }
// This test should be run with an MSA account to validate that the refresh for MSA accounts works properly public async Task AuthenticateWithMSAWithSubsequentSilentRefresh() { var cred = new InteractiveBrowserCredential(); // this should pop browser var authRecord = await cred.AuthenticateAsync(); Assert.NotNull(authRecord); // this should not pop browser AccessToken token = await cred.GetTokenAsync(new TokenRequestContext(new string[] { "https://vault.azure.net/.default" })).ConfigureAwait(false); Assert.NotNull(token.Token); }
public static async Task <TokenCredential> GetUserCredentialAsync() { if (!File.Exists(AUTH_RECORD_PATH)) { #region Snippet:Identity_ClientSideUserAuthentication_Persist_TokenCache var credential = new InteractiveBrowserCredential( new InteractiveBrowserCredentialOptions { TokenCachePersistenceOptions = new TokenCachePersistenceOptions() }); #endregion #region Snippet:Identity_ClientSideUserAuthentication_Persist_AuthRecord AuthenticationRecord authRecord = await credential.AuthenticateAsync(); using (var authRecordStream = new FileStream(AUTH_RECORD_PATH, FileMode.Create, FileAccess.Write)) { await authRecord.SerializeAsync(authRecordStream); } #endregion return(credential); } else { #region Snippet:Identity_ClientSideUserAuthentication_Persist_SilentAuth AuthenticationRecord authRecord; using (var authRecordStream = new FileStream(AUTH_RECORD_PATH, FileMode.Open, FileAccess.Read)) { authRecord = await AuthenticationRecord.DeserializeAsync(authRecordStream); } var credential = new InteractiveBrowserCredential( new InteractiveBrowserCredentialOptions { TokenCachePersistenceOptions = new TokenCachePersistenceOptions(), AuthenticationRecord = authRecord }); #endregion return(credential); } }
public async Task AuthenticateWithSharedTokenCacheAsync() { var cred = new InteractiveBrowserCredential(new InteractiveBrowserCredentialOptions { TokenCache = new PersistentTokenCache() }); // this should pop browser AuthenticationRecord record = await cred.AuthenticateAsync(); var cred2 = new InteractiveBrowserCredential(new InteractiveBrowserCredentialOptions { TokenCache = new PersistentTokenCache(), AuthenticationRecord = record }); // this should not pop browser AccessToken token = await cred2.GetTokenAsync(new TokenRequestContext(new string[] { "https://vault.azure.net/.default" })).ConfigureAwait(false); Assert.NotNull(token.Token); }
static async Task Main(string[] args) { // var cred = new DefaultAzureCredential(); // var token = cred.GetTokenAsync( // new TokenRequestContext(scopes: new string[] { "your scope here" }) { } // ); // 1. Create TokenCredential object with TokenCachePersistenceOptions set var credentialOne = new InteractiveBrowserCredential( new InteractiveBrowserCredentialOptions { TokenCachePersistenceOptions = new TokenCachePersistenceOptions() { Name = "AuthenticationRecord.cache" } }); // 2. Prompt user to authenticate AuthenticationRecord authRecordWrite = await credentialOne.AuthenticateAsync(); // 3. Save AuthenticationRecord to disk using (var authRecordStreamWrite = new FileStream("AuthRecord.json", FileMode.Create, FileAccess.Write)) { await authRecordWrite.SerializeAsync(authRecordStreamWrite); } // A future user session where we want to silent auth with TokenCache and AuthenticationRecord // 4. Read the AuthenticationRecord from disk AuthenticationRecord authRecordRead; using (var authRecordStreamRead = new FileStream("AuthRecord.json", FileMode.Open, FileAccess.Read)) { authRecordRead = await AuthenticationRecord.DeserializeAsync(authRecordStreamRead); } // 5. Create TokenCredential object with TokenCache and use persisted AuthenticationRecord var credentialTwo = new InteractiveBrowserCredential( new InteractiveBrowserCredentialOptions { TokenCachePersistenceOptions = new TokenCachePersistenceOptions() { Name = "AuthenticationRecord.cache" }, AuthenticationRecord = authRecordRead }); // 5.1 Same as above but with DisableAutomaticAuthentication set to true // var credentialTwo = new InteractiveBrowserCredential( // new InteractiveBrowserCredentialOptions // { // TokenCachePersistenceOptions = new TokenCachePersistenceOptions() // { // Name = "AuthenticationRecord.cache" // }, // AuthenticationRecord = authRecordRead, // DisableAutomaticAuthentication = true // }); // 6. Use the new TokenCredential object. User will not be prompted to re-authenticate if token has expired. var client = new SecretClient(new Uri("https://memealyzerdevkv.vault.azure.net/"), credentialTwo); try { var secret = await client.GetSecretAsync("CosmosKey"); Console.WriteLine(secret.Value.Value); } catch (AuthenticationRequiredException ex) { Console.WriteLine("You set InteractiveBrowserCredentialOptions.DisableAutomaticAuthentication to true and the user token has expired or has been revoked."); Console.WriteLine(ex.ToString()); } }