public void CredentialsConstructorThrowsForInvalidValues() { TokenCache cache = new TestTokenCache(); var settings = ActiveDirectoryServiceSettings.Azure; Assert.ThrowsAsync <ArgumentOutOfRangeException>(() => UserTokenProvider.LoginSilentAsync(null, "microsoft.onmicrosoft.com", this._username, this._password, cache)); Assert.ThrowsAsync <ArgumentOutOfRangeException>(() => UserTokenProvider.LoginWithPromptAsync( "microsoft.onmicrosoft.com", ActiveDirectoryClientSettings.UsePromptOnly(string.Empty, new Uri("urn:ietf:wg:oauth:2.0:oob")), settings, cache)); Assert.ThrowsAsync <ArgumentOutOfRangeException>(() => UserTokenProvider.LoginWithPromptAsync(null, ActiveDirectoryClientSettings.UsePromptOnly("1950a258-227b-4e31-a9cf-717495945fc2", new Uri("urn:ietf:wg:oauth:2.0:oob")), settings, cache)); Assert.ThrowsAsync <ArgumentOutOfRangeException>(() => UserTokenProvider.LoginWithPromptAsync(string.Empty, ActiveDirectoryClientSettings.UsePromptOnly("1950a258-227b-4e31-a9cf-717495945fc2", new Uri("urn:ietf:wg:oauth:2.0:oob")), settings, cache)); Assert.ThrowsAsync <AuthenticationException>(() => UserTokenProvider.LoginSilentAsync("1950a258-227b-4e31-a9cf-717495945fc2", "microsoft.onmicrosoft.com", null, this._password, cache)); Assert.Throws <AuthenticationException>(() => UserTokenProvider.LoginSilentAsync("1950a258-227b-4e31-a9cf-717495945fc2", "microsoft.onmicrosoft.com", string.Empty, this._password, cache).ConfigureAwait(false).GetAwaiter().GetResult()); Assert.ThrowsAsync <AuthenticationException>(() => UserTokenProvider.LoginSilentAsync("1950a258-227b-4e31-a9cf-717495945fc2", "microsoft.onmicrosoft.com", this._username, null, cache)); Assert.ThrowsAsync <AuthenticationException>(() => UserTokenProvider.LoginSilentAsync("1950a258-227b-4e31-a9cf-717495945fc2", "microsoft.onmicrosoft.com", this._username, string.Empty, cache)); }
/// <summary> /// Acquire Graph token /// </summary> /// <param name="graphAADServiceSettings"></param> /// <param name="spnClientId"></param> /// <param name="spnSecret"></param> /// <param name="userName"></param> /// <param name="password"></param> /// <param name="psClientId"></param> private void UpdateTokenInfoWithGraphToken(ActiveDirectoryServiceSettings graphAADServiceSettings, string spnClientId = "", string spnSecret = "", string userName = "", string password = "", string psClientId = "") { Task <TokenCredentials> graphAuthResult = null; try { if (!string.IsNullOrWhiteSpace(userName) && !string.IsNullOrWhiteSpace(password)) { //#if FullNetFx #if net452 graphAuthResult = Task.Run(async() => (TokenCredentials)await UserTokenProvider .LoginSilentAsync(psClientId, this.Tenant, userName, password, graphAADServiceSettings).ConfigureAwait(continueOnCapturedContext: false)); #endif } else if (!string.IsNullOrWhiteSpace(spnClientId) && !string.IsNullOrWhiteSpace(spnSecret)) { graphAuthResult = Task.Run(async() => (TokenCredentials)await ApplicationTokenProvider .LoginSilentAsync(this.Tenant, spnClientId, spnSecret, graphAADServiceSettings).ConfigureAwait(continueOnCapturedContext: false)); } this.TokenInfo[TokenAudience.Graph] = graphAuthResult?.Result; } catch (Exception ex) { Debug.WriteLine(string.Format("Error while acquiring Graph Token: '{0}'", ex.ToString())); // Not all accounts are registered to have access to Graph endpoints. } }
public async override Task ProcessHttpRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var adSettings = new ActiveDirectoryServiceSettings { AuthenticationEndpoint = new Uri(Environment.AuthenticationEndpoint), TokenAudience = new Uri(Environment.ManagementEndpoint), ValidateAuthority = true }; string url = request.RequestUri.ToString(); if (url.StartsWith(Environment.GraphEndpoint, StringComparison.OrdinalIgnoreCase)) { adSettings.TokenAudience = new Uri(Environment.GraphEndpoint); } if (!credentialsCache.ContainsKey(adSettings.TokenAudience)) { if (servicePrincipalLoginInformation != null) { if (servicePrincipalLoginInformation.ClientSecret != null) { credentialsCache[adSettings.TokenAudience] = await ApplicationTokenProvider.LoginSilentAsync( TenantId, servicePrincipalLoginInformation.ClientId, servicePrincipalLoginInformation.ClientSecret, adSettings, TokenCache.DefaultShared); } #if NET45 else if (servicePrincipalLoginInformation.X509Certificate != null) { credentialsCache[adSettings.TokenAudience] = await ApplicationTokenProvider.LoginSilentAsync( TenantId, new ClientAssertionCertificate(servicePrincipalLoginInformation.ClientId, servicePrincipalLoginInformation.X509Certificate), adSettings, TokenCache.DefaultShared); } #endif else { credentialsCache[adSettings.TokenAudience] = await ApplicationTokenProvider.LoginSilentAsync( TenantId, servicePrincipalLoginInformation.ClientId, servicePrincipalLoginInformation.Certificate, servicePrincipalLoginInformation.CertificatePassword, adSettings, TokenCache.DefaultShared); } } #if !PORTABLE else if (userLoginInformation != null) { credentialsCache[adSettings.TokenAudience] = await UserTokenProvider.LoginSilentAsync( userLoginInformation.ClientId, TenantId, userLoginInformation.UserName, userLoginInformation.Password, adSettings, TokenCache.DefaultShared); } #endif #if PORTABLE else if (deviceCredentialInformation != null) { credentialsCache[adSettings.TokenAudience] = await UserTokenProvider.LoginByDeviceCodeAsync( deviceCredentialInformation.ClientId, TenantId, adSettings, TokenCache.DefaultShared, deviceCredentialInformation.DeviceCodeFlowHandler); } #endif else if (msiTokenProviderFactory != null) { credentialsCache[adSettings.TokenAudience] = new TokenCredentials(this.msiTokenProviderFactory.Create(adSettings.TokenAudience.OriginalString)); } } await credentialsCache[adSettings.TokenAudience].ProcessHttpRequestAsync(request, cancellationToken); }
public void SilentUserLogin(string cnnStr) { LiteralCnnString = cnnStr; ServiceClientCredentials svcClientCred = null; svcClientCred = UserTokenProvider.LoginSilentAsync(this.ClientId, this.TenantId, this.UserName, this.Password, ActiveDirectoryServiceSettings.AzureGermany).GetAwaiter().GetResult(); Assert.NotNull(svcClientCred); }
public void OrgIdCredentialWorksWithoutDialog() { var credentials = UserTokenProvider.LoginSilentAsync("1950a258-227b-4e31-a9cf-717495945fc2", this._domain, this._username, this._password).GetAwaiter().GetResult(); var client = new HttpClient(); var request = new HttpRequestMessage(HttpMethod.Get, new Uri("https://management.azure.com/subscriptions?api-version=2014-04-01-preview")); credentials.ProcessHttpRequestAsync(request, CancellationToken.None).Wait(); Assert.NotNull(request.Headers.Authorization); var response = client.SendAsync(request).ConfigureAwait(false).GetAwaiter().GetResult(); Assert.Equal(HttpStatusCode.OK, response.StatusCode); }
public void OrgIdCredentialsThrowsForInvalidCredentials() { var exception = Assert.Throws <AuthenticationException>(() => UserTokenProvider.LoginSilentAsync("1950a258-227b-4e31-a9cf-717495945fc2", this._domain, "*****@*****.**", "This is not a valid password").GetAwaiter().GetResult()); Assert.NotNull(exception.InnerException); Assert.Equal(typeof(AdalException), exception.InnerException.GetType()); exception = Assert.Throws <AuthenticationException>(() => UserTokenProvider.LoginSilentAsync("1950a258-227b-4e31-a9cf-717495945fc2", this._domain, "bad_user@bad_domain.com", this._password).ConfigureAwait(false).GetAwaiter().GetResult()); Assert.NotNull(exception.InnerException); Assert.Equal(typeof(AdalException), exception.InnerException.GetType()); exception = Assert.Throws <AuthenticationException>(() => UserTokenProvider.LoginSilentAsync("1950a258-227b-4e31-a9cf-717495945fc2", "not-a-valid-domain", this._username, this._password).ConfigureAwait(false).GetAwaiter().GetResult()); Assert.NotNull(exception.InnerException); Assert.Equal(typeof(AdalServiceException), exception.InnerException.GetType()); exception = Assert.Throws <AuthenticationException>(() => UserTokenProvider.LoginSilentAsync("not-a-valid-client-id", this._domain, this._username, this._password) .ConfigureAwait(false).GetAwaiter().GetResult()); Assert.NotNull(exception.InnerException); Assert.Equal(typeof(AdalServiceException), exception.InnerException.GetType()); }
public static ServiceClientCredentials LoginAzureRM(this ICakeContext ctx, string tenantId, string loginName, string password) { if (string.IsNullOrWhiteSpace(tenantId)) { throw new ArgumentNullException(nameof(tenantId)); } if (string.IsNullOrWhiteSpace(loginName)) { throw new ArgumentNullException(nameof(loginName)); } if (string.IsNullOrWhiteSpace(password)) { throw new ArgumentNullException(nameof(password)); } return(UserTokenProvider.LoginSilentAsync(WELLKNOWN_CLIENTID, tenantId, loginName, password).GetAwaiter().GetResult()); }
private static async Task LoginUserAsync( Dictionary <TokenAudience, TokenCredentials> tokens, string domain, string username, string password, TestEndpoints endpoints) { var mgmSettings = new ActiveDirectoryServiceSettings() { AuthenticationEndpoint = new Uri(endpoints.AADAuthUri.ToString() + domain), TokenAudience = endpoints.AADTokenAudienceUri }; var grpSettings = new ActiveDirectoryServiceSettings() { AuthenticationEndpoint = new Uri(endpoints.AADAuthUri.ToString() + domain), TokenAudience = endpoints.GraphTokenAudienceUri }; var mgmAuthResult = (TokenCredentials)await UserTokenProvider .LoginSilentAsync(TestEnvironment.ClientIdDefault, domain, username, password, mgmSettings) .ConfigureAwait(false); try { var graphAuthResult = (TokenCredentials)await UserTokenProvider .LoginSilentAsync(TestEnvironment.ClientIdDefault, domain, username, password, grpSettings) .ConfigureAwait(false); tokens[TokenAudience.Graph] = graphAuthResult; } catch { // Not all accounts are registered to have access to Graph endpoints. } tokens[TokenAudience.Management] = mgmAuthResult; }
private static string localFilePropertyDumpPath = @"C:\Data"; // Used for Acl/DiskUsage Dump public static void Main(string[] args) { try { // Acquire token and create client using user id and password - Shown for illustration purposes, Comment following two lines if you are not authenticating with userid and password ServiceClientCredentials clientCreds1 = UserTokenProvider.LoginSilentAsync(clientId, domain, UserId, Psswd).GetAwaiter().GetResult(); AdlsClient client1 = AdlsClient.CreateClient(clientAccountPath, clientCreds1); // Acquire token and create client using client secret and client id var creds = new ClientCredential(clientId, clientSecret); ServiceClientCredentials clientCreds2 = ApplicationTokenProvider.LoginSilentAsync(domain, creds).GetAwaiter().GetResult(); AdlsClient client2 = AdlsClient.CreateClient(clientAccountPath, clientCreds2); // Perform write with flush and read with seek PerformWriteFlushReadSeek(client2); // Concatenate two files PerformConcat(client2); // Get Content summary using async operations GetContentSummaryAsync(client2).GetAwaiter().GetResult(); // Bulk upload and download RunFileTransfer(client2); // Change Acl and get acl and disk usage properties SetAclAndGetFileProperties(client2); // Illustrate token refresh TestTokenRefresh(client2); } catch (AdlsException e) { PrintAdlsException(e); } Console.WriteLine("Done. Press ENTER to continue ..."); Console.ReadLine(); }
/// <summary> /// Login /// </summary> private void Login() { string userPassword = this.ConnectionString.GetValue(ConnectionStringKeys.PasswordKey); string spnClientId = this.ConnectionString.GetValue(ConnectionStringKeys.ServicePrincipalKey); string spnSecret = this.ConnectionString.GetValue(ConnectionStringKeys.ServicePrincipalSecretKey); //We use this because when login silently using userTokenProvider, we need to provide a well known ClientId for an app that has delegating permissions. //All first party app have that permissions, so we use PowerShell app ClientId string PowerShellClientId = "1950a258-227b-4e31-a9cf-717495945fc2"; /* * Currently we prioritize login as below: * 1) ServicePrincipal/ServicePrincipal Secret Key * 2) UserName / Password combination * 3) Interactive Login (where user will be presented with prompt to login) */ #region Login #region aadSettings ActiveDirectoryServiceSettings aadServiceSettings = new ActiveDirectoryServiceSettings() { AuthenticationEndpoint = new Uri(this.Endpoints.AADAuthUri.ToString() + this.ConnectionString.GetValue(ConnectionStringKeys.AADTenantKey)), TokenAudience = this.Endpoints.AADTokenAudienceUri }; ActiveDirectoryServiceSettings graphAADServiceSettings = new ActiveDirectoryServiceSettings() { AuthenticationEndpoint = new Uri(this.Endpoints.AADAuthUri.ToString() + this.ConnectionString.GetValue(ConnectionStringKeys.AADTenantKey)), TokenAudience = this.Endpoints.GraphTokenAudienceUri }; #endregion if ((!string.IsNullOrEmpty(spnClientId)) && (!string.IsNullOrEmpty(spnSecret))) { Task <TokenCredentials> mgmAuthResult = Task.Run(async() => (TokenCredentials)await ApplicationTokenProvider .LoginSilentAsync(this.Tenant, spnClientId, spnSecret, aadServiceSettings).ConfigureAwait(continueOnCapturedContext: false)); this.TokenInfo[TokenAudience.Management] = mgmAuthResult.Result; UpdateTokenInfoWithGraphToken(graphAADServiceSettings, spnClientId: spnClientId, spnSecret: spnSecret); } else if ((!string.IsNullOrEmpty(this.UserName)) && (!string.IsNullOrEmpty(userPassword))) { //#if FullNetFx #if net452 Task <TokenCredentials> mgmAuthResult = Task.Run(async() => (TokenCredentials)await UserTokenProvider .LoginSilentAsync(PowerShellClientId, this.Tenant, this.UserName, userPassword, aadServiceSettings).ConfigureAwait(continueOnCapturedContext: false)); this.TokenInfo[TokenAudience.Management] = mgmAuthResult.Result; UpdateTokenInfoWithGraphToken(graphAADServiceSettings, userName: this.UserName, password: userPassword, psClientId: PowerShellClientId); #else throw new NotSupportedException("Username/Password login is supported only in NET452 and above projects"); #endif } else { //#if FullNetFx #if net452 InteractiveLogin(this.Tenant, PowerShellClientId, aadServiceSettings, graphAADServiceSettings); #else throw new NotSupportedException("Interactive Login is supported only in NET452 and above projects"); #endif } #endregion }
public async override Task ProcessHttpRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var adSettings = new ActiveDirectoryServiceSettings { AuthenticationEndpoint = new Uri(Environment.AuthenticationEndpoint), TokenAudience = new Uri(Environment.ManagementEndpoint), ValidateAuthority = true }; string url = request.RequestUri.ToString(); if (url.StartsWith(Environment.GraphEndpoint, StringComparison.OrdinalIgnoreCase)) { adSettings.TokenAudience = new Uri(Environment.GraphEndpoint); } string host = request.RequestUri.Host; if (host.EndsWith(Environment.KeyVaultSuffix, StringComparison.OrdinalIgnoreCase)) { var resource = new Uri(Regex.Replace(Environment.KeyVaultSuffix, "^.", "https://")); if (credentialsCache.ContainsKey(new Uri(Regex.Replace(Environment.KeyVaultSuffix, "^.", "https://")))) { adSettings.TokenAudience = resource; } else { using (var r = new HttpRequestMessage(request.Method, url)) { var response = await new HttpClient().SendAsync(r).ConfigureAwait(false); if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized && response.Headers.WwwAuthenticate != null) { var header = response.Headers.WwwAuthenticate.ElementAt(0).ToString(); var regex = new Regex("authorization=\"([^\"]+)\""); var match = regex.Match(header); adSettings.AuthenticationEndpoint = new Uri(match.Groups[1].Value); regex = new Regex("resource=\"([^\"]+)\""); match = regex.Match(header); adSettings.TokenAudience = new Uri(match.Groups[1].Value); } } } } if (!credentialsCache.ContainsKey(adSettings.TokenAudience)) { if (servicePrincipalLoginInformation != null) { if (servicePrincipalLoginInformation.ClientId == null) { throw new RestException($"Cannot communicate with server. ServicePrincipalLoginInformation should contain a valid ClientId information."); } if (servicePrincipalLoginInformation.ClientSecret != null) { credentialsCache[adSettings.TokenAudience] = await ApplicationTokenProvider.LoginSilentAsync( TenantId, servicePrincipalLoginInformation.ClientId, servicePrincipalLoginInformation.ClientSecret, adSettings, TokenCache.DefaultShared); } #if NET45 else if (servicePrincipalLoginInformation.X509Certificate != null) { credentialsCache[adSettings.TokenAudience] = await ApplicationTokenProvider.LoginSilentAsync( TenantId, new ClientAssertionCertificate(servicePrincipalLoginInformation.ClientId, servicePrincipalLoginInformation.X509Certificate), adSettings, TokenCache.DefaultShared); } #else else if (servicePrincipalLoginInformation.X509Certificate != null) { credentialsCache[adSettings.TokenAudience] = await ApplicationTokenProvider.LoginSilentAsync( TenantId, new Microsoft.Rest.Azure.Authentication.ClientAssertionCertificate(servicePrincipalLoginInformation.ClientId, servicePrincipalLoginInformation.X509Certificate), adSettings, TokenCache.DefaultShared); } #endif else if (servicePrincipalLoginInformation.Certificate != null) { credentialsCache[adSettings.TokenAudience] = await ApplicationTokenProvider.LoginSilentAsync( TenantId, servicePrincipalLoginInformation.ClientId, servicePrincipalLoginInformation.Certificate, servicePrincipalLoginInformation.CertificatePassword, adSettings, TokenCache.DefaultShared); } else { throw new RestException($"Cannot communicate with server. ServicePrincipalLoginInformation should contain either a valid ClientSecret or Certificate information."); } } #if NET45 else if (userLoginInformation != null) { credentialsCache[adSettings.TokenAudience] = await UserTokenProvider.LoginSilentAsync( userLoginInformation.ClientId, TenantId, userLoginInformation.UserName, userLoginInformation.Password, adSettings, TokenCache.DefaultShared); } #else else if (deviceCredentialInformation != null) { credentialsCache[adSettings.TokenAudience] = await UserTokenProvider.LoginByDeviceCodeAsync( deviceCredentialInformation.ClientId, TenantId, adSettings, TokenCache.DefaultShared, deviceCredentialInformation.DeviceCodeFlowHandler); } #endif else if (msiTokenProviderFactory != null) { credentialsCache[adSettings.TokenAudience] = new TokenCredentials(this.msiTokenProviderFactory.Create(adSettings.TokenAudience.OriginalString)); } // no token available for communication else { throw new RestException($"Cannot communicate with server. No authentication token available for '{adSettings.TokenAudience}'."); } } await credentialsCache[adSettings.TokenAudience].ProcessHttpRequestAsync(request, cancellationToken); }