private static Task <string> AcquireTokenAsync(string authorityURL, string userID, string password) => Task.Run(() => { // The below properties are set specific to test configurations. string scope = "https://database.windows.net//.default"; string applicationName = "Microsoft Data SqlClient Manual Tests"; string clientVersion = "1.0.0.0"; string adoClientId = "4d079b4c-cab7-4b7c-a115-8fd51b6f8239"; IPublicClientApplication app = PublicClientApplicationBuilder.Create(adoClientId) .WithAuthority(authorityURL) .WithClientName(applicationName) .WithClientVersion(clientVersion) .Build(); AuthenticationResult result; string[] scopes = new string[] { scope }; // Note: CorrelationId, which existed in ADAL, can not be set in MSAL (yet?). // parameter.ConnectionId was passed as the CorrelationId in ADAL to aid support in troubleshooting. // If/When MSAL adds CorrelationId support, it should be passed from parameters here, too. SecureString securePassword = new SecureString(); foreach (char c in password) { securePassword.AppendChar(c); } securePassword.MakeReadOnly(); result = app.AcquireTokenByUsernamePassword(scopes, userID, securePassword).ExecuteAsync().Result; return(result.AccessToken); });
private async Task RunAcquireTokenWithUsernameIncorrectPasswordAsync( IPublicClientApplication msalPublicClient, string userName) { SecureString incorrectSecurePassword = new SecureString(); incorrectSecurePassword.AppendChar('x'); incorrectSecurePassword.MakeReadOnly(); try { var result = await msalPublicClient .AcquireTokenByUsernamePassword(s_scopes, userName, incorrectSecurePassword) .WithCorrelationId(CorrelationId) .ExecuteAsync(CancellationToken.None) .ConfigureAwait(false); } catch (MsalServiceException ex) { Assert.IsTrue(!string.IsNullOrWhiteSpace(ex.CorrelationId)); Assert.AreEqual(400, ex.StatusCode); Assert.AreEqual(InvalidGrantError, ex.ErrorCode); Assert.IsTrue(ex.Message.StartsWith("AADSTS50126")); return; } Assert.Fail("Bad exception or no exception thrown"); }
/// <summary> /// Get token. /// </summary> public override Task <SqlAuthenticationToken> AcquireTokenAsync(SqlAuthenticationParameters parameters) => Task.Run(() => { IPublicClientApplication app = PublicClientApplicationBuilder.Create(ActiveDirectoryAuthentication.AdoClientId) .WithAuthority(parameters.Authority) .WithClientName(Common.DbConnectionStringDefaults.ApplicationName) .WithClientVersion(Common.ADP.GetAssemblyVersion().ToString()) .Build(); AuthenticationResult result; string scope = parameters.Resource.EndsWith(s_defaultScopeSuffix) ? parameters.Resource : parameters.Resource + s_defaultScopeSuffix; string[] scopes = new string[] { scope }; // Note: CorrelationId, which existed in ADAL, can not be set in MSAL (yet?). // parameter.ConnectionId was passed as the CorrelationId in ADAL to aid support in troubleshooting. // If/When MSAL adds CorrelationId support, it should be passed from parameters here, too. SecureString password = new SecureString(); foreach (char c in parameters.Password) { password.AppendChar(c); } password.MakeReadOnly(); result = app.AcquireTokenByUsernamePassword(scopes, parameters.UserId, password).ExecuteAsync().Result; return(new SqlAuthenticationToken(result.AccessToken, result.ExpiresOn)); });
protected async Task <GetTokenForTeamsUserOptions> CreateTeamsUserParams() { GetTokenForTeamsUserOptions options = new GetTokenForTeamsUserOptions("Sanitized", "Sanitized", "Sanitized"); if (!TestEnvironment.ShouldIgnoreIdentityExchangeTokenTest && Mode != RecordedTestMode.Playback) { IPublicClientApplication publicClientApplication = PublicClientApplicationBuilder.Create(TestEnvironment.CommunicationM365AppId) .WithAuthority(TestEnvironment.CommunicationM365AadAuthority + "/" + TestEnvironment.CommunicationM365AadTenant) .WithRedirectUri(TestEnvironment.CommunicationM365RedirectUri) .Build(); string[] scopes = { TestEnvironment.CommunicationM365Scope }; SecureString communicationMsalPassword = new SecureString(); foreach (char c in TestEnvironment.CommunicationMsalPassword) { communicationMsalPassword.AppendChar(c); } AuthenticationResult result = await publicClientApplication.AcquireTokenByUsernamePassword( scopes, TestEnvironment.CommunicationMsalUsername, communicationMsalPassword).ExecuteAsync(CancellationToken.None).ConfigureAwait(false); options = new GetTokenForTeamsUserOptions(result.AccessToken, TestEnvironment.CommunicationM365AppId, result.UniqueId); } return(options); }
// Get an access token for the given context and resourceId. An attempt is first made to // acquire the token silently. If that fails, then we try to acquire the token by prompting the user. public async Task <GraphServiceClient> GetAuthenticatedClient() { if (_graphClient == null) { // Create Microsoft Graph client. try { // Build a client application. IPublicClientApplication publicClientApplication = PublicClientApplicationBuilder.Create(ClientId) .WithAuthority($"{Instance}{TenantId}") .WithDefaultRedirectUri() .Build(); try { var password = new NetworkCredential(UserId, Password).SecurePassword; await publicClientApplication.AcquireTokenByUsernamePassword(Scopes, UserId, password) .ExecuteAsync(); } catch (Exception) { try { var accounts = (await publicClientApplication.GetAccountsAsync()).ToArray(); await publicClientApplication.AcquireTokenInteractive(Scopes) .WithAccount(accounts.FirstOrDefault()) .WithPrompt(Prompt.SelectAccount) .ExecuteAsync(); } catch (MsalException msalex) { Debug.WriteLine($"Error Acquiring Token:{System.Environment.NewLine}{msalex}"); } } // Create an authentication provider by passing in a client application and graph scopes. DeviceCodeProvider authProvider = new DeviceCodeProvider(publicClientApplication, Scopes); ClientApp = publicClientApplication; // Create a new instance of GraphServiceClient with the authentication provider. // And this is the place where problem is being thrown, that it's unable to load NewtonSoft 6.0.0.0 // But most intriguing part is that, when this code is called from project "Scheduler", it works just fine // But once it's called from the Project "Job.Import", it all goes wrong and error is thrown // All of this led me to think that something is wrong with Quartz.net _graphClient = new GraphServiceClient(authProvider); return(_graphClient); } catch (Exception ex) { Debug.WriteLine("Could not create a graph client: " + ex.Message); } } return(_graphClient); }
private async Task <AuthenticationResult> DoAuthentication() { AuthenticationResult authenticationResult = null; if (AuthenticationType.Equals("MasterUser")) { IPublicClientApplication clientApp = PublicClientApplicationBuilder .Create(ApplicationId) .WithAuthority(AuthorityUrl) .Build(); var userAccounts = await clientApp.GetAccountsAsync(); try { authenticationResult = await clientApp.AcquireTokenSilent(Scope, userAccounts.FirstOrDefault()).ExecuteAsync(); } catch (MsalUiRequiredException) { try { SecureString password = new SecureString(); foreach (var key in Password) { password.AppendChar(key); } authenticationResult = await clientApp.AcquireTokenByUsernamePassword(Scope, Username, password).ExecuteAsync(); } catch (MsalException) { throw; } } } else if (AuthenticationType.Equals("ServicePrincipal")) { // For app only authentication, we need the specific tenant id in the authority url var tenantSpecificURL = AuthorityUrl.Replace("organizations", Tenant); IConfidentialClientApplication clientApp = ConfidentialClientApplicationBuilder .Create(ApplicationId) .WithClientSecret(ApplicationSecret) .WithAuthority(tenantSpecificURL) .Build(); try { authenticationResult = await clientApp.AcquireTokenForClient(Scope).ExecuteAsync(); } catch (MsalException) { throw; } } return(authenticationResult); }
/// <summary> /// Tries to acquire a delegated Microsoft Graph Access Token for the provided scopes using the provided credentials /// </summary> /// <param name="clientId">ClientId to use to acquire the token. Required.</param> /// <param name="scopes">Array with scopes that should be requested access to. Required.</param> /// <param name="username">The username to authenticate with. Required.</param> /// <param name="securePassword">The password to authenticate with. Required.</param> /// <returns><see cref="GraphToken"/> instance with the token</returns> public static GenericToken AcquireDelegatedTokenWithCredentials(string clientId, string[] scopes, string authority, string username, SecureString securePassword) { if (string.IsNullOrEmpty(clientId)) { throw new ArgumentNullException(nameof(clientId)); } if (scopes == null || scopes.Length == 0) { throw new ArgumentNullException(nameof(scopes)); } if (string.IsNullOrEmpty(username)) { throw new ArgumentNullException(nameof(username)); } if (securePassword == null || securePassword.Length == 0) { throw new ArgumentNullException(nameof(securePassword)); } AuthenticationResult tokenResult = null; if (publicClientApplication == null) { publicClientApplication = PublicClientApplicationBuilder.Create(clientId).WithAuthority(authority).Build(); } var account = publicClientApplication.GetAccountsAsync().GetAwaiter().GetResult(); try { tokenResult = publicClientApplication.AcquireTokenSilent(scopes, account.First()).ExecuteAsync().GetAwaiter().GetResult(); } catch { try { tokenResult = publicClientApplication.AcquireTokenByUsernamePassword(scopes, username, securePassword).ExecuteAsync().GetAwaiter().GetResult(); } catch (MsalUiRequiredException msalEx) { if (msalEx.Classification == UiRequiredExceptionClassification.ConsentRequired) { if (clientId == PnPConnection.PnPManagementShellClientId) { throw new PSInvalidOperationException("Please provide consent to the PnP Management Shell application with 'Register-PnPManagementShellAccess'"); } else { throw msalEx; } } } } return(new GenericToken(tokenResult.AccessToken)); }
private async Task <AuthenticationResult> AuthenticateByUsernamePassword(IPublicClientApplication clientApp) { SecureString password = new SecureString(); foreach (var key in _azureAdOptions.Password) { password.AppendChar(key); } return(await clientApp.AcquireTokenByUsernamePassword(_azureAdOptions.Scope, _azureAdOptions.Username, password) .ExecuteAsync()); }
private void Authenticate() { //var accounts = _clientApp.GetAccountsAsync() // .GetAwaiter().GetResult(); var result = _clientApp.AcquireTokenByUsernamePassword(_scopes, UserName, Password) .ExecuteAsync().GetAwaiter().GetResult(); if (result == null) { throw new Exception("Failed to authenticate!"); } DisplayName = result.Account.Username; _token = result.AccessToken; _expiresOn = result.ExpiresOn; }
private static async Task <AuthenticationResult> AcquireTokenROPCAsync( IPublicClientApplication pca) { if (string.IsNullOrEmpty(Config.Username) || string.IsNullOrEmpty(Config.Password)) { throw new InvalidOperationException("Please configure a username and password!"); } return(await pca.AcquireTokenByUsernamePassword( Config.Scopes, Config.Username, Config.Password) .ExecuteAsync() .ConfigureAwait(false)); }
static void Main(string[] args) { string flag = "Y"; IPublicClientApplication app = PublicClientApplicationBuilder.Create("60ef0838-f145-4f00-b7ba-a5af7f31cc3c").Build(); string[] scopes = new string[] { "api://4a673722-5437-4663-bba7-5f49372e06ba/Group.All", "openid" }; do { List <IAccount> list = app.GetAccountsAsync().GetAwaiter().GetResult().ToList(); Console.WriteLine("Checking cache"); if (list.Count > 0) { Console.WriteLine($"Find {list.Count}"); list.ForEach(_ => { Console.WriteLine($"Acquire a new token for {_.Username}"); AuthenticationResult result = app.AcquireTokenSilent(scopes, _).WithForceRefresh(true).WithAuthority("https://login.microsoftonline.com/e4c9ab4e-bd27-40d5-8459-230ba2a757fb/").ExecuteAsync().Result; Console.WriteLine($"New token -> {result.AccessToken}"); }); } else { Console.WriteLine("No cache"); try { var securePassword = new SecureString(); // Test AcquireTokenByUsernamePassword foreach (char c in "**********") { securePassword.AppendChar(c); } AuthenticationResult result = app.AcquireTokenByUsernamePassword(scopes, "*****@*****.**", securePassword).WithAuthority("https://login.microsoftonline.com/e4c9ab4e-bd27-40d5-8459-230ba2a757fb/").ExecuteAsync().GetAwaiter().GetResult(); // Test AcquireTokenInteractive //AuthenticationResult result = app.AcquireTokenInteractive(scopes).WithAuthority("https://login.microsoftonline.com/e4c9ab4e-bd27-40d5-8459-230ba2a757fb/").ExecuteAsync().Result; Console.WriteLine(result.Account.Username + " -> " + result.AccessToken); } catch (Exception e) { Console.Error.WriteLine(e.Message); Console.Error.WriteLine(e.StackTrace); } } Console.Write("Continue? Y/N:"); flag = Console.ReadLine(); } while (flag.Trim().ToUpper().Equals("Y")); Console.ReadLine(); }
public async Task SilentAuth_ForceRefresh_Async() { var labResponse = await LabUserHelper.GetDefaultUserAsync().ConfigureAwait(false); pca = PublicClientApplicationBuilder .Create(labResponse.App.AppId) .WithAuthority("https://login.microsoftonline.com/organizations") .Build(); Trace.WriteLine("Part 1 - Acquire a token with U/P"); AuthenticationResult authResult = await pca .AcquireTokenByUsernamePassword(s_scopes, labResponse.User.Upn, new NetworkCredential("", labResponse.User.GetOrFetchPassword()).SecurePassword) .ExecuteAsync(new CancellationTokenSource().Token) .ConfigureAwait(false); await ValidateAuthResultAsync(authResult, labResponse).ConfigureAwait(false); }
/// <summary> /// Get Access token /// </summary> /// <returns>Access token</returns> public static async Task <string> GetAccessToken() { AuthenticationResult authenticationResult = null; if (ConfigValidatorService.AuthenticationType.Equals("masteruser", StringComparison.InvariantCultureIgnoreCase)) { IPublicClientApplication clientApp = PublicClientApplicationBuilder .Create(ConfigValidatorService.ApplicationId) .WithAuthority(m_authorityUrl) .Build(); var userAccounts = await clientApp.GetAccountsAsync(); try { authenticationResult = await clientApp.AcquireTokenSilent(m_scope, userAccounts.FirstOrDefault()).ExecuteAsync(); } catch (MsalUiRequiredException) { SecureString secureStringPassword = new SecureString(); foreach (var key in ConfigValidatorService.Password) { secureStringPassword.AppendChar(key); } authenticationResult = await clientApp.AcquireTokenByUsernamePassword(m_scope, ConfigValidatorService.Username, secureStringPassword).ExecuteAsync(); } } // Service Principal auth is recommended by Microsoft to achieve App Owns Data Power BI embedding else if (ConfigValidatorService.AuthenticationType.Equals("serviceprincipal", StringComparison.InvariantCultureIgnoreCase)) { // For app only authentication, we need the specific tenant id in the authority url var tenantSpecificURL = m_authorityUrl.Replace("organizations", ConfigValidatorService.Tenant); IConfidentialClientApplication clientApp = ConfidentialClientApplicationBuilder .Create(ConfigValidatorService.ApplicationId) .WithClientSecret(ConfigValidatorService.ApplicationSecret) .WithAuthority(tenantSpecificURL) .Build(); authenticationResult = await clientApp.AcquireTokenForClient(m_scope).ExecuteAsync(); } return(authenticationResult.AccessToken); }
/// <summary> /// Generates and returns Access token /// </summary> /// <returns>AAD token</returns> public string GetAccessToken() { AuthenticationResult authenticationResult = null; if (azureAd.Value.AuthenticationMode.Equals("masteruser", StringComparison.InvariantCultureIgnoreCase)) { // Create a public client to authorize the app with the AAD app IPublicClientApplication clientApp = PublicClientApplicationBuilder.Create(azureAd.Value.ClientId).WithAuthority(azureAd.Value.AuthorityUri).Build(); var userAccounts = clientApp.GetAccountsAsync().Result; try { // Retrieve Access token from cache if available authenticationResult = clientApp.AcquireTokenSilent(azureAd.Value.Scope, userAccounts.FirstOrDefault()).ExecuteAsync().Result; } catch (MsalUiRequiredException) { SecureString password = new SecureString(); foreach (var key in azureAd.Value.PbiPassword) { password.AppendChar(key); } authenticationResult = clientApp.AcquireTokenByUsernamePassword(azureAd.Value.Scope, azureAd.Value.PbiUsername, password).ExecuteAsync().Result; } } // Service Principal auth is the recommended by Microsoft to achieve App Owns Data Power BI embedding else if (azureAd.Value.AuthenticationMode.Equals("serviceprincipal", StringComparison.InvariantCultureIgnoreCase)) { // For app only authentication, we need the specific tenant id in the authority url var tenantSpecificUrl = azureAd.Value.AuthorityUri.Replace("organizations", azureAd.Value.TenantId); // Create a confidential client to authorize the app with the AAD app IConfidentialClientApplication clientApp = ConfidentialClientApplicationBuilder .Create(azureAd.Value.ClientId) .WithClientSecret(azureAd.Value.ClientSecret) .WithAuthority(tenantSpecificUrl) .Build(); // Make a client call if Access token is not available in cache authenticationResult = clientApp.AcquireTokenForClient(azureAd.Value.Scope).ExecuteAsync().Result; } return(authenticationResult.AccessToken); }
private async static Task <string> GetDelegateAuthTokenAsync() { if (delegateAuthToken != null && delegateAuthToken.ExpiresOn > DateTimeOffset.UtcNow) { return(delegateAuthToken.AccessToken); } string authority = $"https://login.microsoftonline.com/{Settings.TenantId}"; string[] scopes = new string[] { "openid", "Sites.ReadWrite.All" }; IPublicClientApplication app = PublicClientApplicationBuilder.Create(Settings.ClientId) .WithAuthority(authority) .Build(); var accounts = await app.GetAccountsAsync(); if (accounts.Any()) { delegateAuthToken = await app.AcquireTokenSilent(scopes, accounts.FirstOrDefault()) .ExecuteAsync(); } else { try { var securePassword = new SecureString(); foreach (char c in Settings.DelegatedUserPwd) { securePassword.AppendChar(c); } delegateAuthToken = await app.AcquireTokenByUsernamePassword(scopes, Settings.DelegatedUserName, securePassword) .ExecuteAsync(); } catch (MsalException) { throw new AutoTeamsStructureException("Cannot get delegate token"); } } return(delegateAuthToken.AccessToken); }
/// <summary> /// Obtains a token for a user account, authenticating them using the given username and password. Note: This will fail with /// an <see cref="AuthenticationFailedException"/> if the specified user acound has MFA enabled. /// </summary> /// <param name="scopes">The list of scopes for which the token will have access.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <returns>An <see cref="AccessToken"/> which can be used to authenticate service client calls.</returns> public override async Task <AccessToken> GetTokenAsync(string[] scopes, CancellationToken cancellationToken = default) { using DiagnosticScope scope = _pipeline.Diagnostics.CreateScope("Azure.Identity.UsernamePasswordCredential.GetToken"); scope.Start(); try { AuthenticationResult result = await _pubApp.AcquireTokenByUsernamePassword(scopes, _username, _password).ExecuteAsync(cancellationToken).ConfigureAwait(false); return(new AccessToken(result.AccessToken, result.ExpiresOn)); } catch (Exception e) { scope.Failed(e); throw; } }
/// <summary> /// Tries to acquire a delegated Microsoft Graph Access Token for the provided scopes using the provided credentials /// </summary> /// <param name="clientId">ClientId to use to acquire the token. Required.</param> /// <param name="scopes">Array with scopes that should be requested access to. Required.</param> /// <param name="username">The username to authenticate with. Required.</param> /// <param name="securePassword">The password to authenticate with. Required.</param> /// <returns><see cref="GraphToken"/> instance with the token</returns> public static GenericToken AcquireDelegatedTokenWithCredentials(string clientId, string[] scopes, string username, SecureString securePassword) { var officeManagementApiScopes = Enum.GetNames(typeof(OfficeManagementApiPermission)).Select(s => s.Replace("_", ".")).Intersect(scopes).ToArray(); // Take the remaining scopes and try requesting them from the Microsoft Graph API scopes = scopes.Except(officeManagementApiScopes).ToArray(); if (string.IsNullOrEmpty(clientId)) { throw new ArgumentNullException(nameof(clientId)); } if (scopes == null || scopes.Length == 0) { throw new ArgumentNullException(nameof(scopes)); } if (string.IsNullOrEmpty(username)) { throw new ArgumentNullException(nameof(username)); } if (securePassword == null || securePassword.Length == 0) { throw new ArgumentNullException(nameof(securePassword)); } AuthenticationResult tokenResult = null; if (publicClientApplication == null) { publicClientApplication = PublicClientApplicationBuilder.Create(clientId).WithAuthority($"{OAuthBaseUrl}organizations/").Build(); } var account = publicClientApplication.GetAccountsAsync().GetAwaiter().GetResult(); try { tokenResult = publicClientApplication.AcquireTokenSilent(scopes, account.First()).ExecuteAsync().GetAwaiter().GetResult(); } catch { tokenResult = publicClientApplication.AcquireTokenByUsernamePassword(scopes.Select(s => $"{ResourceIdentifier}/{s}").ToArray(), username, securePassword).ExecuteAsync().GetAwaiter().GetResult(); } return(new GraphToken(tokenResult.AccessToken)); }
/// <summary> /// Tries to acquire a delegated Office 365 Management API Access Token for the provided scopes using the provided credentials /// </summary> /// <param name="clientId">ClientId to use to acquire the token. Required.</param> /// <param name="scopes">Array with scopes that should be requested access to. Required.</param> /// <param name="username">The username to authenticate with. Required.</param> /// <param name="securePassword">The password to authenticate with. Required.</param> /// <returns><see cref="OfficeManagementApiToken"/> instance with the token</returns> public static GenericToken AcquireDelegatedTokenWithCredentials(string clientId, string[] scopes, string username, SecureString securePassword) { if (string.IsNullOrEmpty(clientId)) { throw new ArgumentNullException(nameof(clientId)); } if (scopes == null || scopes.Length == 0) { throw new ArgumentNullException(nameof(scopes)); } if (string.IsNullOrEmpty(username)) { throw new ArgumentNullException(nameof(username)); } if (securePassword == null || securePassword.Length == 0) { throw new ArgumentNullException(nameof(securePassword)); } if (publicClientApplication == null) { publicClientApplication = PublicClientApplicationBuilder.Create(clientId) // Delegated Graph token using credentials is only possible against organizational tenants .WithAuthority($"{OAuthBaseUrl}organizations/") .Build(); } var accounts = confidentialClientApplication.GetAccountsAsync().GetAwaiter().GetResult(); AuthenticationResult tokenResult = null; try { tokenResult = publicClientApplication.AcquireTokenSilent(new[] { $"{ResourceIdentifier}/{DefaultScope}" }, accounts.First()).ExecuteAsync().GetAwaiter().GetResult(); } catch { tokenResult = publicClientApplication.AcquireTokenByUsernamePassword(scopes.Select(s => $"{ResourceIdentifier}/{s}").ToArray(), username, securePassword).ExecuteAsync().GetAwaiter().GetResult(); } return(new GraphToken(tokenResult.AccessToken)); }
private static string GetAccessToken(ConfigurationModel configuration) { // Logic for retrieving the access token AuthenticationResult authenticationResult = null; // Create a public client to authorize the app with the AAD app IPublicClientApplication clientApp = PublicClientApplicationBuilder.Create(configuration.ClientId).WithAuthority(configuration.AuthorityUri).Build(); var userAccounts = clientApp.GetAccountsAsync().Result; try { // Retrieve Access token from cache if available authenticationResult = clientApp.AcquireTokenSilent(configuration.Scope, userAccounts.FirstOrDefault()).ExecuteAsync().Result; } catch (MsalUiRequiredException) { try { SecureString password = new SecureString(); foreach (var key in configuration.PbiPassword) { password.AppendChar(key); } authenticationResult = clientApp.AcquireTokenByUsernamePassword(configuration.Scope, configuration.PbiUsername, password).ExecuteAsync().Result; } catch (MsalException) { throw; } } try { return(authenticationResult.AccessToken); } catch (Exception) { throw; } }
public static async Task <AuthenticationResult> GetAccessToken() { string ApplicationId = ConfigurationManager.AppSettings["ApplicationID"]; string Tenant = ConfigurationManager.AppSettings["TenantId"]; string AuthorityURL = ConfigurationManager.AppSettings["AADAuthorityUri"].Replace("common", Tenant); string[] Scope = ConfigurationManager.AppSettings["scope"].Split(','); string Username = ConfigurationManager.AppSettings["pbiUsername"]; string Password = ConfigurationManager.AppSettings["pbiPassword"]; IPublicClientApplication clientApp = PublicClientApplicationBuilder .Create(ApplicationId) .WithAuthority(AuthorityURL) .WithTenantId(Tenant) .Build(); var userAccounts = await clientApp.GetAccountsAsync(); try { authResult = await clientApp.AcquireTokenSilent(Scope, userAccounts.FirstOrDefault()).ExecuteAsync(); } catch (MsalUiRequiredException) { try { SecureString password = new SecureString(); foreach (var key in Password) { password.AppendChar(key); } authResult = await clientApp.AcquireTokenByUsernamePassword(Scope, Username, password).ExecuteAsync(); } catch (MsalException) { throw; } } return(authResult); }
public async Task <string> ResourceOwnerPasswordAsync() { IPublicClientApplication app = PublicClientApplicationBuilder .Create(clientId) .WithTenantId(tenantId) .Build(); var securePassword = new SecureString(); foreach (char c in password) { securePassword.AppendChar(c); } AuthenticationResult auth = await app.AcquireTokenByUsernamePassword( scopes, username, securePassword) .ExecuteAsync(); return(auth.AccessToken); }
public async Task AuthorityValidationTestWithFalseValidateAuthorityAsync() { LabResponse labResponse = await LabUserHelper.GetDefaultUserAsync().ConfigureAwait(false); LabUser user = labResponse.User; IPublicClientApplication pca = PublicClientApplicationBuilder .Create(labResponse.App.AppId) .WithAuthority("https://bogus.microsoft.com/common", false) .WithTestLogging() .Build(); Trace.WriteLine("Acquire a token using a not so common authority alias"); _ = await AssertException.TaskThrowsAsync <HttpRequestException>(() => pca.AcquireTokenByUsernamePassword( s_scopes, user.Upn, new NetworkCredential("", user.GetOrFetchPassword()).SecurePassword) .ExecuteAsync()) .ConfigureAwait(false); }
/// <summary> /// Gets an access token for the requested resource and scope /// </summary> /// <param name="resource">Resource to request an access token for (unused)</param> /// <param name="scopes">Scopes to request</param> /// <returns>An access token</returns> public override async Task <string> GetAccessTokenAsync(Uri resource, string[] scopes) { if (resource == null) { throw new ArgumentNullException(nameof(resource)); } if (scopes == null) { throw new ArgumentNullException(nameof(scopes)); } AuthenticationResult tokenResult = null; var account = await publicClientApplication.GetAccountsAsync().ConfigureAwait(false); try { // Try to get the token from the tokens cache tokenResult = await publicClientApplication.AcquireTokenSilent(scopes, account.FirstOrDefault()) .ExecuteAsync().ConfigureAwait(false); } catch (MsalUiRequiredException) { // Try to get the token directly through AAD if it is not available in the tokens cache tokenResult = await publicClientApplication.AcquireTokenByUsernamePassword(scopes, Username, Password) .ExecuteAsync().ConfigureAwait(false); } // Log the access token retrieval action Log?.LogInformation(PnPCoreAuthResources.AuthenticationProvider_LogAccessTokenRetrieval, GetType().Name, resource, scopes.Aggregate(string.Empty, (c, n) => c + ", " + n).TrimEnd(',')); // Return the Access Token, if we've got it // In case of any exception while retrieving the access token, // MSAL will throw an exception that we simply bubble up return(tokenResult.AccessToken); }
/// <summary> /// Tries to acquire a delegated Microsoft Graph Access Token for the provided scopes using the provided credentials /// </summary> /// <param name="clientId">ClientId to use to acquire the token. Required.</param> /// <param name="scopes">Array with scopes that should be requested access to. Required.</param> /// <param name="username">The username to authenticate with. Required.</param> /// <param name="securePassword">The password to authenticate with. Required.</param> /// <returns><see cref="GraphToken"/> instance with the token</returns> public static GenericToken AcquireDelegatedTokenWithCredentials(string clientId, string[] scopes, string authority, string username, SecureString securePassword) { if (string.IsNullOrEmpty(clientId)) { throw new ArgumentNullException(nameof(clientId)); } if (scopes == null || scopes.Length == 0) { throw new ArgumentNullException(nameof(scopes)); } if (string.IsNullOrEmpty(username)) { throw new ArgumentNullException(nameof(username)); } if (securePassword == null || securePassword.Length == 0) { throw new ArgumentNullException(nameof(securePassword)); } AuthenticationResult tokenResult = null; if (publicClientApplication == null) { publicClientApplication = PublicClientApplicationBuilder.Create(clientId).WithAuthority(authority).Build(); } var account = publicClientApplication.GetAccountsAsync().GetAwaiter().GetResult(); try { tokenResult = publicClientApplication.AcquireTokenSilent(scopes, account.First()).ExecuteAsync().GetAwaiter().GetResult(); } catch { tokenResult = publicClientApplication.AcquireTokenByUsernamePassword(scopes, username, securePassword).ExecuteAsync().GetAwaiter().GetResult(); } return(new GenericToken(tokenResult.AccessToken)); }
public async Task <string> GetTokenAsync() { if (!string.IsNullOrEmpty(_userId)) { try { var account = await _clientApplication.GetAccountAsync(_userId); if (account != null) { var silentResult = await _clientApplication.AcquireTokenSilent(_scopes, account).ExecuteAsync(); return(silentResult.AccessToken); } } catch (MsalUiRequiredException) { } } var result = await _clientApplication.AcquireTokenByUsernamePassword(_scopes, _username, _password).ExecuteAsync(); _userId = result.Account.HomeAccountId.Identifier; return(result.AccessToken); }
/// <summary> /// Get token. /// </summary> public override Task <SqlAuthenticationToken> AcquireTokenAsync(SqlAuthenticationParameters parameters) => Task.Run(async() => { IPublicClientApplication app = PublicClientApplicationBuilder.Create(ActiveDirectoryAuthentication.AdoClientId) .WithAuthority(parameters.Authority) .WithClientName(Common.DbConnectionStringDefaults.ApplicationName) .WithClientVersion(Common.ADP.GetAssemblyVersion().ToString()) .Build(); AuthenticationResult result; string[] scopes = parameters.Scopes; // Note: CorrelationId, which existed in ADAL, can not be set in MSAL (yet?). // parameter.ConnectionId was passed as the CorrelationId in ADAL to aid support in troubleshooting. // If/When MSAL adds CorrelationId support, it should be passed from parameters here, too. if (parameters.AuthenticationMethod == SqlAuthenticationMethod.ActiveDirectoryIntegrated) { result = app.AcquireTokenByIntegratedWindowsAuth(scopes).ExecuteAsync().Result; } else if (parameters.AuthenticationMethod == SqlAuthenticationMethod.ActiveDirectoryPassword) { SecureString password = new SecureString(); foreach (char c in parameters.Password) { password.AppendChar(c); } password.MakeReadOnly(); result = app.AcquireTokenByUsernamePassword(scopes, parameters.UserId, password).ExecuteAsync().Result; } else { result = await app.AcquireTokenInteractive(scopes) .WithUseEmbeddedWebView(true) .ExecuteAsync(); } return(new SqlAuthenticationToken(result.AccessToken, result.ExpiresOn)); });
/// <summary> /// This method can only be used with <see cref="Authority.Organizations"/> /// </summary> public async Task <string> GetAccessTokenWithUsernamePassword() { if (username == null || password == null) { return(null); } using var cts = new CancellationTokenSource(Timeouts.Silent); var secureString = new SecureString(); foreach (var c in password ?? "") { secureString.AppendChar(c); } try { var result = await msalClient .AcquireTokenByUsernamePassword(Scopes, username, secureString) .ExecuteAsync(cts.Token).ConfigureAwait(false);; CurrentUserAccount = result?.Account; return(result?.AccessToken); } catch (MsalException ex) { Logger.ShowException(ex); return(null); } }
public async Task AuthorityMigrationAsync() { LabResponse labResponse = await LabUserHelper.GetDefaultUserAsync().ConfigureAwait(false); LabUser user = labResponse.User; IPublicClientApplication pca = PublicClientApplicationBuilder .Create(labResponse.App.AppId) .WithAuthority("https://login.windows.net/" + labResponse.Lab.TenantId + "/") .WithTestLogging() .Build(); Trace.WriteLine("Acquire a token using a not so common authority alias"); AuthenticationResult authResult = await pca.AcquireTokenByUsernamePassword( s_scopes, user.Upn, new NetworkCredential("", user.GetOrFetchPassword()).SecurePassword) // BugBug https://identitydivision.visualstudio.com/Engineering/_workitems/edit/776308/ // sts.windows.net fails when doing instance discovery, e.g.: // https://sts.windows.net/common/discovery/instance?api-version=1.1&authorization_endpoint=https%3A%2F%2Fsts.windows.net%2Ff645ad92-e38d-4d1a-b510-d1b09a74a8ca%2Foauth2%2Fv2.0%2Fauthorize .WithAuthority("https://login.windows.net/" + labResponse.Lab.TenantId + "/") .ExecuteAsync() .ConfigureAwait(false); Assert.IsNotNull(authResult.AccessToken); Trace.WriteLine("Acquire a token silently using the common authority alias"); authResult = await pca.AcquireTokenSilent(s_scopes, (await pca.GetAccountsAsync().ConfigureAwait(false)).First()) .WithAuthority("https://login.windows.net/common") .ExecuteAsync() .ConfigureAwait(false); Assert.IsNotNull(authResult.AccessToken); }
private async Task <AuthenticationResult> GetAuthenticationResultWithAssertAsync( LabResponse labResponse, HttpSnifferClientFactory factory, IPublicClientApplication msalPublicClient, string federationMetadata, Guid testCorrelationId) { AuthenticationResult authResult = await msalPublicClient .AcquireTokenByUsernamePassword(s_scopes, labResponse.User.Upn, new NetworkCredential("", labResponse.User.GetOrFetchPassword()).SecurePassword) .WithCorrelationId(testCorrelationId) .WithFederationMetadata(federationMetadata) .ExecuteAsync(CancellationToken.None) .ConfigureAwait(false); Assert.IsNotNull(authResult); Assert.AreEqual(TokenSource.IdentityProvider, authResult.AuthenticationResultMetadata.TokenSource); Assert.IsNotNull(authResult.AccessToken); Assert.IsNotNull(authResult.IdToken); Assert.IsTrue(string.Equals(labResponse.User.Upn, authResult.Account.Username, StringComparison.InvariantCultureIgnoreCase)); AssertTelemetryHeaders(factory, false, labResponse); AssertCcsRoutingInformationIsSent(factory, labResponse); return(authResult); }
private static async Task RunConsoleAppLogicAsync(IPublicClientApplication pca) { while (true) { Console.Clear(); Console.WriteLine("Authority: " + GetAuthority()); await DisplayAccountsAsync(pca).ConfigureAwait(false); // display menu Console.WriteLine(@" 1. IWA 2. Acquire Token with Username and Password 3. Acquire Token with Device Code 4. Acquire Token Interactive 5. Acquire Token Interactive via NetStandard lib 6. Acquire Token Silently 7. Acquire Token Silently - multiple requests in parallel 8. Acquire SSH Cert Interactive c. Clear cache r. Rotate Tenant ID e. Expire all ATs x. Exit app Enter your Selection: "); char.TryParse(Console.ReadLine(), out var selection); Task <AuthenticationResult> authTask = null; try { switch (selection) { case '1': // acquire token authTask = pca.AcquireTokenByIntegratedWindowsAuth(s_scopes).WithUsername(s_username).ExecuteAsync(CancellationToken.None); await FetchTokenAndCallGraphAsync(pca, authTask).ConfigureAwait(false); break; case '2': // acquire token u/p SecureString password = GetPasswordFromConsole(); authTask = pca.AcquireTokenByUsernamePassword(s_scopes, s_username, password).ExecuteAsync(CancellationToken.None); await FetchTokenAndCallGraphAsync(pca, authTask).ConfigureAwait(false); break; case '3': authTask = pca.AcquireTokenWithDeviceCode( s_scopes, deviceCodeResult => { Console.WriteLine(deviceCodeResult.Message); return(Task.FromResult(0)); }).ExecuteAsync(CancellationToken.None); await FetchTokenAndCallGraphAsync(pca, authTask).ConfigureAwait(false); break; case '6': // acquire token silent IAccount account = pca.GetAccountsAsync().Result.FirstOrDefault(); if (account == null) { Log(LogLevel.Error, "Test App Message - no accounts found, AcquireTokenSilentAsync will fail... ", false); } authTask = pca.AcquireTokenSilent(s_scopes, account).ExecuteAsync(CancellationToken.None); await FetchTokenAndCallGraphAsync(pca, authTask).ConfigureAwait(false); break; case '7': // acquire token silent - one request per IAccount var accounts = await pca.GetAccountsAsync().ConfigureAwait(false); Task <AuthenticationResult>[] tasks = accounts .Select(acc => pca.AcquireTokenSilent(s_scopes, acc).ExecuteAsync()) .ToArray(); AuthenticationResult[] result = await Task.WhenAll(tasks).ConfigureAwait(false); foreach (var ar in result) { Console.BackgroundColor = ConsoleColor.DarkGreen; Console.WriteLine($"Got a token for {ar.Account.Username} "); Console.ResetColor(); } break; case '5': // Acquire Token Interactive via NetStandard lib CancellationTokenSource cts2 = new CancellationTokenSource(); var authenticator = new NetStandardAuthenticator(Log, CacheFilePath); await FetchTokenAndCallGraphAsync(pca, authenticator.GetTokenInteractiveAsync(cts2.Token)).ConfigureAwait(false); break; case '8': // acquire SSH cert RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); RSAParameters rsaKeyInfo = rsa.ExportParameters(false); string modulus = Base64UrlHelpers.Encode(rsaKeyInfo.Modulus); string exp = Base64UrlHelpers.Encode(rsaKeyInfo.Exponent); string jwk = $"{{\"kty\":\"RSA\", \"n\":\"{modulus}\", \"e\":\"{exp}\"}}"; CancellationTokenSource cts = new CancellationTokenSource(); authTask = pca.AcquireTokenInteractive(s_scopes) .WithUseEmbeddedWebView(false) .WithExtraQueryParameters(new Dictionary <string, string>() { { "dc", "prod-wst-test1" }, { "slice", "test" }, { "sshcrt", "true" } }) .WithSSHCertificateAuthenticationScheme(jwk, "1") .WithSystemWebViewOptions(new SystemWebViewOptions() { HtmlMessageSuccess = "All good, close the browser!", OpenBrowserAsync = SystemWebViewOptions.OpenWithEdgeBrowserAsync }) .ExecuteAsync(cts.Token); await FetchTokenAndCallGraphAsync(pca, authTask).ConfigureAwait(false); break; case 'c': var accounts2 = await pca.GetAccountsAsync().ConfigureAwait(false); foreach (var acc in accounts2) { await pca.RemoveAsync(acc).ConfigureAwait(false); } break; case 'r': // rotate tid s_currentTid = (s_currentTid + 1) % s_tids.Length; pca = CreatePca(); RunConsoleAppLogicAsync(pca).Wait(); break; case 'e': // expire all ATs var tokenCacheInternal = pca.UserTokenCache as ITokenCacheInternal; var ats = tokenCacheInternal.Accessor.GetAllAccessTokens(); // set access tokens as expired foreach (var accessItem in ats) { accessItem.ExpiresOnUnixTimestamp = ((long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds) .ToString(CultureInfo.InvariantCulture); tokenCacheInternal.Accessor.SaveAccessToken(accessItem); } TokenCacheNotificationArgs args = new TokenCacheNotificationArgs( pca.UserTokenCache as ITokenCacheInternal, s_clientIdForPublicApp, null, true); await tokenCacheInternal.OnAfterAccessAsync(args).ConfigureAwait(false); break; case 'x': return; default: break; } } catch (Exception ex) { Log(LogLevel.Error, ex.Message, false); Log(LogLevel.Error, ex.StackTrace, false); } Console.WriteLine("\n\nHit 'ENTER' to continue..."); Console.ReadLine(); } }