/// <summary> /// Device Update for IoT Hub Sample: Enumerate updates /// </summary> static async Task Main() { Console.WriteLine("Device Update for IoT Hub Sample: Enumerate updates"); Console.WriteLine(); var credentials = new InteractiveBrowserCredential(Constant.TenantId, Constant.ClientId); var client = new DeviceUpdateClient(Constant.AccountEndpoint, Constant.Instance, credentials); Console.WriteLine($"Provider: {Constant.Provider}"); Console.WriteLine($"Name : {Constant.Name}"); Console.WriteLine($"Versions: "); try { var response = client.GetVersionsAsync(Constant.Provider, Constant.Name); await foreach (var version in response) { var versionDoc = JsonDocument.Parse(version.ToMemory()); Console.WriteLine("\t" + versionDoc.RootElement.GetString()); } } catch (RequestFailedException e) { Console.WriteLine(e); throw; } }
/// <summary> /// Device Update for IoT Hub Sample: Delete update version /// </summary> /// <param name="updateVersion">Update version to delete.</param> static async Task Main(string updateVersion) { Console.WriteLine("Device Update for IoT Hub Sample: Delete update version"); Console.WriteLine(); if (string.IsNullOrWhiteSpace(updateVersion)) { throw new ArgumentException("You have to provider a valid update version."); } var credentials = new InteractiveBrowserCredential(Constant.TenantId, Constant.ClientId); var client = new DeviceUpdateClient(Constant.AccountEndpoint, Constant.Instance, credentials); Console.WriteLine("Deleting update:"); Console.WriteLine($" Provider: {Constant.Provider}"); Console.WriteLine($" Name : {Constant.Name}"); Console.WriteLine($" Version : {updateVersion}"); try { var response = await client.DeleteUpdateAsync(true, Constant.Provider, Constant.Name, updateVersion); var doc = JsonDocument.Parse(response.Value.ToMemory()); Console.WriteLine(doc.RootElement.GetProperty("status").ToString()); } catch (RequestFailedException e) { Console.WriteLine(e); throw; } }
public void ValidateConstructorOverload1() { // tests the InteractiveBrowserCredential constructor overload // public InteractiveBrowserCredential(InteractiveBrowserCredentialOptions options) // null var credential = new InteractiveBrowserCredential((InteractiveBrowserCredentialOptions)null); AssertOptionsHonored(new InteractiveBrowserCredentialOptions(), credential); Assert.AreEqual(CredentialPipeline.GetInstance(null), credential.Pipeline); // with options var options = new InteractiveBrowserCredentialOptions { ClientId = Guid.NewGuid().ToString(), TenantId = Guid.NewGuid().ToString(), AuthorityHost = new Uri("https://login.myauthority.com/"), DisableAutomaticAuthentication = true, EnablePersistentCache = true, AllowUnencryptedCache = true, AuthenticationRecord = new AuthenticationRecord() }; credential = new InteractiveBrowserCredential(options); AssertOptionsHonored(options, credential); }
private async Task UploadOrderedInterfaces(IEnumerable <DTInterfaceInfo> orderedInterfaces) { Log.Write("Uploaded interfaces:"); try { var credential = new InteractiveBrowserCredential(options.TenantId, options.ClientId); var client = new DigitalTwinsClient(new UriBuilder("https", options.HostName).Uri, credential); for (int i = 0; i < (orderedInterfaces.Count() / options.BatchSize) + 1; i++) { IEnumerable <DTInterfaceInfo> batch = orderedInterfaces.Skip(i * options.BatchSize).Take(options.BatchSize); Response <DigitalTwinsModelData[]> response = await client.CreateModelsAsync(batch.Select(i => i.GetJsonLdText())); foreach (DTInterfaceInfo @interface in batch) { Log.Ok(@interface.Id.AbsoluteUri); } } } catch (Exception ex) { Log.Error($"Upload failed."); Log.Error(ex.Message); } }
public async Task <ImageCredentials> GetCredentials() { var options = new InteractiveBrowserCredentialOptions() { TenantId = tenantId, }; OnAuthenticating?.Invoke(); var credential = new InteractiveBrowserCredential(options); var client = new SecretClient(new Uri(vaultUrl), credential); // wait for the first request to finish so that // we the user signs in before the other requests // that way the token will be cached and reused for subsequent // requests without requiring signin var name = await client.GetSecretAsync(nameKey); var secrets = await Task.WhenAll( client.GetSecretAsync(serverKey), client.GetSecretAsync(usernameKey), client.GetSecretAsync(passwordKey)); return(new ImageCredentials() { Name = name.Value.Value, Server = secrets[0].Value.Value, Username = secrets[1].Value.Value, Password = secrets[2].Value.Value }); }
static async Task Main(string[] args) { // Define the permission scopes that you need string[] scopes = { "Directory.AccessAsUser.All" }; // Start interactive login session var options = new InteractiveBrowserCredentialOptions() { ClientId = "<client-id>", TenantId = "<tenant-id>", RedirectUri = new Uri("http://localhost") }; // And a TokenCredential implementation var interactiveCredential = new InteractiveBrowserCredential(options); // Create GraphServiceClient instance var graphClient = new GraphServiceClient(interactiveCredential, scopes); // Set variable (in real solution you should rely on UI to collect passwords in a secure way) var currentPassword = "******"; var newPassword = "******"; // Change current user's password await graphClient.Me.ChangePassword(currentPassword, newPassword).Request().PostAsync(); Console.WriteLine("Password changed!"); }
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 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 }
static async Task Main(string[] args) { DigitalTwinsClient client; try { var credential = new InteractiveBrowserCredential(tenantId, clientId); // Open a browser window and allow user to select which account to authenticate with // If you omit this, the browser will only be launched to authenticate the user once, // then will silently acquire access tokens through the users refresh token as long as it's valid. // So if you are switching between AAD accounts, keep this uncommented. var auth_result = credential.Authenticate(); Console.WriteLine($"Sucessfully authenticated as: {auth_result.Username}"); client = new DigitalTwinsClient(new Uri(adtInstanceUrl), credential); AsyncPageable <ModelData> modelList = client.GetModelsAsync(null, true); await foreach (ModelData md in modelList) { Console.WriteLine($"Id: {md.Id}"); } Console.WriteLine("Done"); } catch (Exception e) { Console.WriteLine($"Authentication or client creation error: {e.Message}"); Environment.Exit(0); } }
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 async Task <SqlAuthenticationToken> AcquireTokenAsync(SqlAuthenticationParameters parameters) { Console.WriteLine($"Sql Auth UserId={parameters.UserId}"); TokenCredential tokenCredential; if (parameters.UserId == "LOCALDEV") { tokenCredential = new InteractiveBrowserCredential(); } /* * else if (!string.IsNullOrEmpty(parameters.UserId)) * { * tokenCredential = new ManagedIdentityCredential(parameters.UserId); * } */ else { tokenCredential = new DefaultAzureCredential(); } var token = await tokenCredential.GetTokenAsync(new TokenRequestContext(new[] { "https://database.windows.net/.default" }), default); var sqlToken = new SqlAuthenticationToken(token.Token, token.ExpiresOn); return(sqlToken); }
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)); }
public async Task SilentAuthenticateWithBrokerAsync() { TokenCachePersistenceOptions persistenceOptions = new TokenCachePersistenceOptions(); // to fully manually verify the InteractiveBrowserCredential this test should be run both authenticating with a // school / organization account as well as a personal live account, i.e. a @outlook.com, @live.com, or @hotmail.com var cred = new InteractiveBrowserCredential(new InteractiveBrowserCredentialBrokerOptions { TokenCachePersistenceOptions = persistenceOptions }); AccessToken token = await cred.GetTokenAsync(new TokenRequestContext(new string[] { "https://vault.azure.net/.default" })).ConfigureAwait(false); Assert.NotNull(token.Token); var silentCred = new SharedTokenCacheCredential(new SharedTokenCacheCredentialBrokerOptions()); // The calls below this should be silent and not require user interaction token = await cred.GetTokenAsync(new TokenRequestContext(new string[] { "https://vault.azure.net/.default" })).ConfigureAwait(false); Assert.NotNull(token.Token); token = await cred.GetTokenAsync(new TokenRequestContext(new string[] { "https://management.core.windows.net//.default" })).ConfigureAwait(false); Assert.NotNull(token.Token); }
/// <summary> /// Illustrates how to construct a <see cref="DigitalTwinsClient"/> including client options, /// using the <see cref="InteractiveBrowserCredential"/> implementation of <see cref="Azure.Core.TokenCredential"/>. /// </summary> /// <param name="tenantId">The Id of the tenant of the application Id.</param> /// <param name="clientId">The application Id.</param> /// <param name="adtEndpoint">The endpoint of the digital twins instance.</param> /// <param name="httpClient">An HttpClient instance for the client to use</param> private static DigitalTwinsClient GetDigitalTwinsClient(string tenantId, string clientId, string adtEndpoint, HttpClient httpClient) { #region Snippet:DigitalTwinsSampleCreateServiceClientInteractiveLogin // This illustrates how to specify client options, in this case, by providing an // instance of HttpClient for the digital twins client to use. var clientOptions = new DigitalTwinsClientOptions { Transport = new HttpClientTransport(httpClient), }; // By using the InteractiveBrowserCredential, the current user can login using a web browser // interactively with the AAD var tokenCredential = new InteractiveBrowserCredential( tenantId, clientId, new TokenCredentialOptions { AuthorityHost = KnownAuthorityHosts.AzureCloud }); var dtClient = new DigitalTwinsClient( new Uri(adtEndpoint), tokenCredential, clientOptions); #endregion Snippet:DigitalTwinsSampleCreateServiceClientInteractiveLogin return(dtClient); }
/// <summary> /// Device Update for IoT Hub Sample: Get device /// </summary> /// <param name="device">Device identifier.</param> static async Task Main(string device) { Console.WriteLine("Device Update for IoT Hub Sample: Get device"); Console.WriteLine(); if (string.IsNullOrWhiteSpace(device)) { throw new ArgumentException("You have to provider a valid device identifier."); } var credentials = new InteractiveBrowserCredential(Constant.TenantId, Constant.ClientId); var client = new DeviceManagementClient(Constant.AccountEndpoint, Constant.Instance, credentials); Console.WriteLine("Retrieve device information:"); Console.WriteLine($" Device: {device}"); Console.WriteLine(); Console.WriteLine("Information:"); try { var response = await client.GetDeviceAsync(device); Console.WriteLine(response.Content.ToString()); } catch (RequestFailedException e) { Console.WriteLine(e); throw; } }
public static async Task Main() { var tokenCache = await ReadTokenCacheAsync(); var credential = new InteractiveBrowserCredential(new InteractiveBrowserCredentialOptions { TokenCache = tokenCache }); }
public void Identity_TokenCache_PersistentDefault() { #region Snippet:Identity_TokenCache_PersistentDefault var credential = new InteractiveBrowserCredential(new InteractiveBrowserCredentialOptions { TokenCache = new PersistentTokenCache() }); #endregion }
/// <summary> /// Get interactive user credentials for Azure Devops. /// </summary> /// <returns>AzDO Credentials</returns> private static async Task <VssCredentials> GetInteractiveUserCredentials() { var browserCredential = new InteractiveBrowserCredential(); var context = new TokenRequestContext(AzureDevOpsAuthScopes); var authToken = await browserCredential.GetTokenAsync(context, System.Threading.CancellationToken.None); return(new VssCredentials(new VssBasicCredential("", authToken.Token))); }
public async Task AuthenticateWithBrowserSingleTenantAsync() { var cred = new InteractiveBrowserCredential(TenantId, SingleTenantClientId); AccessToken token = await cred.GetTokenAsync(new TokenRequestContext(new string[] { "https://vault.azure.net/.default" })).ConfigureAwait(false); Assert.NotNull(token.Token); }
public void InteractiveBrowserCredentialCtorNullTenantId() { var clientId = Guid.NewGuid().ToString(); // validate no exception is thrown when setting TenantId to null var cred = new InteractiveBrowserCredential(null, clientId); cred = new InteractiveBrowserCredential(null, clientId, new TokenCredentialOptions()); }
/// <inheritdoc/> public InteractiveBrowserCredential GetCredential() { if (_credential == null) { _credential = new InteractiveBrowserCredential(_settings.TenantId, _settings.ClientId); } return(_credential); }
static async Task Main() { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { int width = Math.Min(Console.LargestWindowWidth, 150); int height = Math.Min(Console.LargestWindowHeight, 40); Console.SetWindowSize(width, height); } try { // Read configuration data from the IConfiguration config = new ConfigurationBuilder() .AddJsonFile("serviceConfig.json", false, true) .Build(); clientId = config["clientId"]; tenantId = config["tenantId"]; adtInstanceUrl = config["instanceUrl"]; } catch (Exception e) { Log.Error($"Could not read service configuration file serviceConfig.json"); Log.Alert($"Please copy serviceConfig.json.TEMPLATE to serviceConfig.json"); Log.Alert($"and edit to reflect your service connection settings."); Log.Alert($"Make sure that 'Copy always' or 'Copy if newer' is set for serviceConfig.json in VS file properties"); Environment.Exit(0); } Log.Ok("Authenticating..."); try { var credential = new InteractiveBrowserCredential(tenantId, clientId); client = new DigitalTwinsClient(new Uri(adtInstanceUrl), credential); // force authentication to happen here try { client.GetDigitalTwin("---"); } catch (RequestFailedException rex) { } catch (Exception e) { Log.Error($"Authentication or client creation error: {e.Message}"); Log.Alert($"Have you checked that the configuration in serviceConfig.json is correct?"); Environment.Exit(0); } } catch (Exception e) { Log.Error($"Authentication or client creation error: {e.Message}"); Log.Alert($"Have you checked that the configuration in serviceConfig.json is correct?"); Environment.Exit(0); } Log.Ok($"Service client created – ready to go"); CommandLoop CommandLoopInst = new CommandLoop(client); await CommandLoopInst.CliCommandInterpreter(); }
public async Task AuthenticateWithBrowserAsync() { // to fully manually verify the InteractiveBrowserCredential this test should be run both authenticating with a // school / organization account as well as a personal live account, i.e. a @outlook.com, @live.com, or @hotmail.com var cred = new InteractiveBrowserCredential(); AccessToken token = await cred.GetTokenAsync(new TokenRequestContext(new string[] { "https://vault.azure.net/.default" })).ConfigureAwait(false); Assert.NotNull(token.Token); }
public void ConfigureInteractiveBrowserToUseBroker() { #region Snippet:ConfigureInteractiveBrowserToUseBroker // Create an interactive browser credential which will use the system authentication broker var credential = new InteractiveBrowserCredential(new InteractiveBrowserCredentialBrokerOptions()); // Use the credential to authenticate a secret client var client = new SecretClient(new Uri("https://myvault.vault.azure.net/"), credential); #endregion }
public DigitalTwin() { var credential = new InteractiveBrowserCredential(tenantId, clientId); DigitalTwinsClient client = new DigitalTwinsClient(new Uri(adtInstanceUrl), credential); Utils.IgnoreErrors(() => client.GetDigitalTwin("")); _client = client; _commandLoop = new CommandLoop(client); }
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 void AuthenticateBrowserCancellationAsync() { var cred = new InteractiveBrowserCredential(); var cancelSource = new CancellationTokenSource(); ValueTask <AccessToken> getTokenTask = cred.GetTokenAsync(new TokenRequestContext(new string[] { "https://vault.azure.net/.default" }), cancelSource.Token); cancelSource.Cancel(); Assert.ThrowsAsync <OperationCanceledException>(async() => await getTokenTask.ConfigureAwait(false)); }
public void Identity_TokenCache_PersistentNamed() { #region Snippet:Identity_TokenCache_PersistentNamed var tokenCache = new PersistentTokenCache(new PersistentTokenCacheOptions { Name = "my_application_name" }); var credential = new InteractiveBrowserCredential(new InteractiveBrowserCredentialOptions { TokenCache = tokenCache }); #endregion }
public void Identity_TokenCache_PersistentUnencrypted() { #region Snippet:Identity_TokenCache_PersistentUnencrypted var tokenCache = new PersistentTokenCache(new PersistentTokenCacheOptions { AllowUnencryptedStorage = true }); var credential = new InteractiveBrowserCredential(new InteractiveBrowserCredentialOptions { TokenCache = tokenCache }); #endregion }
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); }