public async Task <string?> GetTokenSilentAsync(string[] scopes) { try { var accounts = await _msalSdkClient.GetAccountsAsync(); var firstAccount = accounts.FirstOrDefault(); var authResult = await _msalSdkClient .AcquireTokenSilent(scopes, firstAccount) .ExecuteAsync(); return(authResult.AccessToken); } catch (MsalException e) when(e.ErrorCode == "user_null") { // this is fine } catch (MsalException e) { _telemetry.TrackError(e, new Dictionary <string, string> { { "trace", e.StackTrace }, { "scopes", string.Join(",", scopes) } }); } return(""); }
public async Task <LoginResultType> LoginAsync() { if (!NetworkInterface.GetIsNetworkAvailable()) { return(LoginResultType.NoNetworkAvailable); } try { var accounts = await _client.GetAccountsAsync(); _authenticationResult = await _client.AcquireTokenInteractive(_scopes) .WithAccount(accounts.FirstOrDefault()) .ExecuteAsync(); LoggedIn?.Invoke(this, EventArgs.Empty); return(LoginResultType.Success); } catch (MsalClientException ex) { if (ex.ErrorCode == "authentication_canceled") { return(LoginResultType.CancelledByUser); } return(LoginResultType.UnknownError); } catch (Exception) { return(LoginResultType.UnknownError); } }
/// <summary> /// Login User to OneDrive. /// </summary> public async Task Login() { AuthenticationResult authResult = null; IEnumerable <IAccount> accounts = await publicClientApplication.GetAccountsAsync(); // let's see if we have a user in our belly already try { IAccount firstAccount = accounts.FirstOrDefault(); authResult = await publicClientApplication.AcquireTokenSilent(scopes, firstAccount).ExecuteAsync(); } catch (MsalUiRequiredException) { // pop the browser for the interactive experience authResult = await publicClientApplication.AcquireTokenInteractive(scopes) .WithParentActivityOrWindow( ParentActivityWrapper .ParentActivity) // this is required for Android .ExecuteAsync(); } GraphServiceClient = new GraphServiceClient(new DelegateAuthenticationProvider((requestMessage) => { requestMessage .Headers .Authorization = new AuthenticationHeaderValue("bearer", authResult.AccessToken); return(Task.FromResult(0)); })); }
public async Task <string> GetAccessTokenForUserApiAsync(IEnumerable <string> scopes = null) { var accounts = await pca.GetAccountsAsync(); AuthenticationResult authenticationResult; if (scopes == null) { // Generate the scope, concat of Domain/ClientId/ScopeName scopes = new List <string>(); foreach (var apiScope in this.ApiScopes) { string scope = $"https://{AzureAdOptions.Domain}/{AzureAdOptions.ClientId}/{apiScope}"; ((List <string>)scopes).Add(scope); } } try { authenticationResult = await pca.AcquireTokenSilent(scopes, accounts.FirstOrDefault()).ExecuteAsync(); } catch (MsalUiRequiredException) { authenticationResult = await AcquireByDeviceCodeAsync(pca, scopes); } return(authenticationResult.AccessToken); }
public async Task <bool> LoginSilentAsync(Func <StoryNode> lazynode) { var node = lazynode(); Initialize(); var ret = false; try { var accounts = await clientApp.GetAccountsAsync(); var firstAccount = accounts.FirstOrDefault(); authResult = await clientApp .AcquireTokenSilent(scopes, accounts.FirstOrDefault()) .ExecuteAsync(node.CTS.Token); // Login automatically IsAuthenticated = true; ret = true; } catch (MsalUiRequiredException) { authResult = null; } catch (Exception ex) { authResult = null; node.MessageBuffer?.WriteLine($"Acquiring Token Silently:"); node.MessageBuffer?.WriteLine(ex.Message); node.MessageBuffer?.WriteLine("(E101)"); } return(ret); }
/// <summary> /// Tries to acquire an application Office 365 Management API Access Token for the provided scopes interactively by allowing the user to log in /// </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> /// <returns><see cref="OfficeManagementApiToken"/> instance with the token</returns> public static GenericToken AcquireApplicationTokenInteractive(string clientId, string[] scopes) { if (string.IsNullOrEmpty(clientId)) { throw new ArgumentNullException(nameof(clientId)); } if (scopes == null || scopes.Length == 0) { throw new ArgumentNullException(nameof(scopes)); } if (publicClientApplication == null) { publicClientApplication = PublicClientApplicationBuilder.Create(clientId).WithRedirectUri("https://login.microsoftonline.com/common/oauth2/nativeclient").Build(); } var accounts = publicClientApplication.GetAccountsAsync().GetAwaiter().GetResult(); AuthenticationResult tokenResult = null; try { tokenResult = publicClientApplication.AcquireTokenSilent(new[] { $"{ResourceIdentifier}/{DefaultScope}" }, accounts.First()).ExecuteAsync().GetAwaiter().GetResult(); } catch { tokenResult = publicClientApplication.AcquireTokenInteractive(scopes.Select(s => $"{ResourceIdentifier}/{s}").ToArray()).ExecuteAsync().GetAwaiter().GetResult(); } return(new OfficeManagementApiToken(tokenResult.AccessToken)); }
private async Task Login() { var account = (await _appClient.GetAccountsAsync()).FirstOrDefault(); try { _authResult = await _appClient.AcquireTokenSilent(_scopes, account).ExecuteAsync(); } catch (MsalUiRequiredException ex) { try { _authResult = await _appClient .AcquireTokenInteractive(_scopes) .WithAccount(account) .ExecuteAsync(); } catch (MsalException msalEx) { MessageBox.Show(msalEx.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
/// <summary> /// Call Login /// </summary> private async void SignInButton_Click(object sender, RoutedEventArgs e) { if (_clientApp != null) { var accounts = await _clientApp.GetAccountsAsync(); if (accounts.Any()) { try { await _clientApp.RemoveAsync(accounts.FirstOrDefault()); _clientApp = null; } catch (MsalException ex) { ResultText.Text = $"Error signing-out user: {ex.Message}"; } } } ComboBoxItem authority = Authority.SelectedItem as ComboBoxItem; _clientApp = PublicClientApplicationBuilder.Create(App.ClientId) .WithAuthority(AzureCloudInstance.AzurePublic, authority.Tag as String) .Build(); TokenCacheHelper.EnableSerialization(_clientApp.UserTokenCache); ComboBoxItem scopes = Scopes.SelectedItem as ComboBoxItem; var ScopesString = scopes.Tag as String; string[] scopesRequest = ScopesString.Split(' '); AuthAndCallAPI(null, scopesRequest); }
/// <summary> /// Tries to acquire an application Microsoft Graph Access Token for the provided scopes interactively by allowing the user to log in /// </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> /// <returns><see cref="GraphToken"/> instance with the token</returns> public static GenericToken AcquireApplicationTokenInteractive(string clientId, string[] scopes, AzureEnvironment azureEnvironment) { var endPoint = GetAzureADLoginEndPoint(azureEnvironment); if (string.IsNullOrEmpty(clientId)) { throw new ArgumentNullException(nameof(clientId)); } if (scopes == null || scopes.Length == 0) { throw new ArgumentNullException(nameof(scopes)); } if (publicClientApplication == null) { publicClientApplication = PublicClientApplicationBuilder.Create(clientId).WithRedirectUri($"{endPoint}/common/oauth2/nativeclient").Build(); } AuthenticationResult tokenResult = null; var account = publicClientApplication.GetAccountsAsync().GetAwaiter().GetResult(); try { tokenResult = publicClientApplication.AcquireTokenSilent(scopes, account.First()).ExecuteAsync().GetAwaiter().GetResult(); } catch { tokenResult = publicClientApplication.AcquireTokenInteractive(scopes).ExecuteAsync().GetAwaiter().GetResult(); } return(new GenericToken(tokenResult.AccessToken)); }
public async Task InitializeGraphClientAsync() { var currentAccounts = await _pca.GetAccountsAsync().ConfigureAwait(false); try { if (!currentAccounts.Any()) { throw new Exception("No accounts found"); } // Initialize Graph client _graphClient = new GraphServiceClient(new DelegateAuthenticationProvider( async(requestMessage) => { var result = await _pca.AcquireTokenSilent(Scopes, currentAccounts.FirstOrDefault()) .ExecuteAsync().ConfigureAwait(false); requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken); })); } catch (Exception ex) { Debug.WriteLine("Failed to initialized graph client."); Debug.WriteLine($"Accounts in the msal cache: {currentAccounts.Count()}."); Debug.WriteLine($"See exception message for details: {ex.Message}"); } }
public async Task AuthenticateRequestAsync(HttpRequestMessage request) { if (string.IsNullOrEmpty(_authToken)) { var result = await _application.AcquireTokenWithDeviceCode(_scopes, callback => { string[] parts = callback.Message.Split(' '); var code = parts[Array.FindIndex(parts, a => a.Trim() == "code") + 1]; TextCopy.Clipboard.SetText(code); OpenBrowser("https://www.microsoft.com/devicelogin"); Console.WriteLine(callback.Message); return(Task.FromResult(0)); }).ExecuteAsync(); _authResult = result; _authToken = result.AccessToken; var accounts = await _application.GetAccountsAsync(); _account = accounts.FirstOrDefault(); } if (_authResult.ExpiresOn.ToLocalTime() <= DateTime.Now) { var result = await _application.AcquireTokenSilent(_scopes, _account).ExecuteAsync(); _authResult = result; _authToken = result.AccessToken; var accounts = await _application.GetAccountsAsync(); _account = accounts.FirstOrDefault(); } request.Headers.Authorization = new AuthenticationHeaderValue("bearer", _authToken); }
async Task <string> ICloudStorage.AcquireTokenAsync() { AuthenticationResult authResult = null; IEnumerable <IAccount> accounts = await PCA.GetAccountsAsync(); try { try { IAccount firstAccount = accounts.FirstOrDefault(); authResult = await PCA.AcquireTokenSilent(Scopes, firstAccount).ExecuteAsync(); } catch (MsalUiRequiredException) { try { authResult = await PCA.AcquireTokenInteractive(Scopes) .WithParentActivityOrWindow(parentwindow) .ExecuteAsync(); } catch (Exception ex2) { throw new CloudSignInException("Acquire token interactive failed: " + ex2.Message); } } return(authResult.AccessToken); } catch (Exception ex) { throw new CloudSignInException("Authentication failed: " + ex.Message); } }
/// <summary> /// Login User to OneDrive. /// </summary> public async Task LoginAsync() { AuthenticationResult? authResult = null; IEnumerable <IAccount> accounts = await publicClientApplication.GetAccountsAsync(); // let's see if we have a user in our belly already try { IAccount firstAccount = accounts.FirstOrDefault(); authResult = await publicClientApplication.AcquireTokenSilent(scopes, firstAccount).ExecuteAsync(); GraphServiceClient = graphClientFactory.CreateClient(authResult); } catch (MsalUiRequiredException ex) { logManager.Debug(ex); // pop the browser for the interactive experience authResult = await publicClientApplication.AcquireTokenInteractive(scopes) .WithParentActivityOrWindow(ParentActivityWrapper.ParentActivity) // this is required for Android .ExecuteAsync(); } catch (MsalClientException ex) { if (ex.ErrorCode == ERROR_CODE_CANCELED) { logManager.Info(ex); throw new BackupOperationCanceledException(); } logManager.Error(ex); throw; } }
public static async Task <AuthenticationResult> InitializeWithInteractiveProviderAsync() { var accounts = await pca.GetAccountsAsync(); try { var builder = pca.AcquireTokenInteractive(OAuthenticationSettings.Scopes) .WithAccount(accounts.FirstOrDefault()) .WithPrompt(Microsoft.Identity.Client.Prompt.SelectAccount); if (App.AuthenticationUiParent != null) { builder = builder .WithParentActivityOrWindow(App.AuthenticationUiParent); } #if NETFX_CORE || __ANDROID__ || __IOS__ builder.WithUseEmbeddedWebView(true); #endif var result = await builder.ExecuteAsync(); return(result); } catch (Exception exception) { throw exception; //await Dialogs.ExceptionDialogAsync(exception); //return null; } }
public async Task SignInAsync() { accounts = (await _app.GetAccountsAsync()).ToList(); AuthenticationResult = null; try { AuthenticationResult = await _app.AcquireTokenInteractive(Scopes) .WithUseEmbeddedWebView(false) .WithAccount(accounts.FirstOrDefault()) //.WithPrompt(Prompt.SelectAccount) .ExecuteAsync(); accounts = (await _app.GetAccountsAsync()).ToList(); } catch (MsalUiRequiredException) { } catch (MsalException ex) { // An unexpected error occurred. string message = ex.Message; if (ex.InnerException != null) { message += "Error Code: " + ex.ErrorCode + "Inner Exception : " + ex.InnerException.Message; } MessageBox.Show(message); } }
public async Task <string> AcquireTokenAsync() { var accounts = await _application.GetAccountsAsync(); var token = await AcquireTokenAsync(accounts); return(token.AccessToken); }
public async Task <string> Login() { string userInfo = ""; // get available accounts from user token cache var accounts = await pca.GetAccountsAsync(); AuthenticationResult result; try { // try to acquire token silently result = await pca.AcquireTokenSilent(_scopes, accounts.FirstOrDefault()).ExecuteAsync(); } catch (MsalUiRequiredException) { try { // if not, try interactive authentication session result = await pca.AcquireTokenInteractive( _scopes) .WithPrompt(Prompt.ForceLogin) .ExecuteAsync(); // now query the graph api using the access token if (result != null) { try { string endpoint = "https://graph.microsoft.com/v1.0/me"; HttpRequestMessage request = new HttpRequestMessage( HttpMethod.Get, endpoint); request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue( "Bearer", result.AccessToken); HttpResponseMessage response = await _client.SendAsync( request); userInfo = await response.Content.ReadAsStringAsync(); } catch (HttpRequestException e) { Console.WriteLine("Exception: {0}", e.Message); } } } catch (MsalClientException e) { Console.WriteLine(e.Message); } } return(userInfo); }
public async Task <bool> SignInAsync() { try { IEnumerable <IAccount> accounts = await _pca.GetAccountsAsync().ConfigureAwait(false); IAccount firstAccount = accounts.FirstOrDefault(); AuthenticationResult authResult = await _pca.AcquireTokenSilent(Scopes, firstAccount) .ExecuteAsync().ConfigureAwait(false); // Store the access token securely for later use. string authToken = authResult?.AccessToken; await SecureStorage.SetAsync("AccessToken", authToken).ConfigureAwait(false); AuthorizedDelegate?.Invoke(authToken); string savedToken = await SecureStorage.GetAsync("AccessToken").ConfigureAwait(false); Debug.WriteLine("STORED TOKEN: " + (savedToken != null ? savedToken?.ToString() : "Not Saved")); return(true); } catch (MsalUiRequiredException) { try { // This means we need to login again through the MSAL window. AuthenticationResult authResult = await _pca.AcquireTokenInteractive(Scopes) .WithParentActivityOrWindow(ParentWindow) .ExecuteAsync().ConfigureAwait(false); // Store the access token securely for later use. string authToken = authResult?.AccessToken; await SecureStorage.SetAsync("AccessToken", authToken).ConfigureAwait(false); AuthorizedDelegate?.Invoke(authToken); string savedToken = await SecureStorage.GetAsync("AccessToken").ConfigureAwait(false); Debug.WriteLine("MSAL TOKEN: " + (savedToken != null ? savedToken?.ToString() : "Not Saved")); return(true); } catch (Exception ex2) { Debug.WriteLine(ex2.ToString()); return(false); } } catch (Exception ex) { Debug.WriteLine(ex.ToString()); return(false); } }
private async void ShowCacheCountAsync(object sender, RoutedEventArgs e) { var accounts = await _pca.GetAccountsAsync().ConfigureAwait(false); await DisplayMessageAsync( $"There are {accounts.Count()} in the token cache. " + Environment.NewLine + string.Join(", ", accounts.Select(a => a.Username))).ConfigureAwait(false); }
async Task AcquireToken() { IEnumerable <IAccount> accounts = await PCA.GetAccountsAsync(); AuthenticationResult ar = await PCA.AcquireTokenSilent(Scopes, GetAccountByPolicy(accounts, PolicySignUpSignIn)) .WithB2CAuthority(Authority) .ExecuteAsync(); await UpdateUserInfo(ar); }
/// <summary> /// Clears the cache /// </summary> /// <param name="app"></param> private async Task ClearCache(IPublicClientApplication app) { var accounts = (await app.GetAccountsAsync()).ToList(); while (accounts.Any()) { await app.RemoveAsync(accounts.First()); accounts = (await app.GetAccountsAsync()).ToList(); } }
/// <summary> /// 注销操作 /// </summary> public async void SignOutAsync() { var accounts = await pca.GetAccountsAsync(); while (accounts.Any()) { await pca.RemoveAsync(accounts.First()); accounts = await pca.GetAccountsAsync(); } }
/// <summary> /// Get Token for User. /// </summary> /// <returns>Token for user.</returns> public static async void ClearCache() { var accounts = (await _app.GetAccountsAsync()).ToList(); while (accounts.Any()) { await _app.RemoveAsync(accounts.First()); accounts = (await _app.GetAccountsAsync()).ToList(); } }
/// <summary> /// Get the main user account. /// </summary> public async Task <IAccount> GetUserAccount() { var accounts = await identityClientApp.GetAccountsAsync(); if (accounts == null || !accounts.Any()) { return(null); } return(accounts.First()); }
/// <summary> /// Signs the user out of the service. /// </summary> public static void SignOut() { IdentityClientApp.GetAccountsAsync(); foreach (var user in IdentityClientApp.GetAccountsAsync().Result) { //user.SignOut (); } graphClient = null; TokenForUser = null; }
private async Task <UserContext> SignInInteractively() { IEnumerable <IAccount> accounts = await _pca.GetAccountsAsync(); AuthenticationResult authResult = await _pca.AcquireTokenInteractive(B2CConstants.Scopes) .WithAccount(GetAccountByPolicy(accounts, B2CConstants.PolicySignUpSignIn)) .ExecuteAsync(); var newContext = UpdateUserInfo(authResult); return(newContext); }
private async Task <UserContext> AcquireToken() { IEnumerable <IAccount> accounts = await Pca.GetAccountsAsync(); AuthenticationResult authResult = await Pca.AcquireTokenSilent(B2CConstants.Scopes, GetAccountByPolicy(accounts, B2CConstants.PolicySignUpSignIn)) .WithB2CAuthority(B2CConstants.AuthoritySignInSignUp) .ExecuteAsync(); var newContext = UpdateUserInfo(authResult); return(newContext); }
private async void SignIn(object sender, RoutedEventArgs e) { var accounts = (await _app.GetAccountsAsync()).ToList(); if (SignInButton.Content.ToString() == ClearCacheString) { TodoList.ItemsSource = string.Empty; while (accounts.Any()) { await _app.RemoveAsync(accounts.First()); accounts = (await _app.GetAccountsAsync()).ToList(); } SignInButton.Content = SignInString; UserName.Content = TodoListClient.Resources.UserNotSignedIn; } try { var result = await _app.AcquireTokenInteractive(Scopes) .WithAccount(accounts.FirstOrDefault()) .WithPrompt(Prompt.SelectAccount) .ExecuteAsync() .ConfigureAwait(false); Dispatcher.Invoke(() => { SignInButton.Content = ClearCacheString; SetUserName(result.Account); GetTodoList(); }); } catch (MsalException ex) { if (ex.ErrorCode == "access_denied") { // The user canceled sign in, take no action. } else { string message = ex.Message; if (ex.InnerException != null) { message += "Error Code: " + ex.ErrorCode + "Inner Exception : " + ex.InnerException.Message; } MessageBox.Show(message); } UserName.Content = TodoListClient.Resources.UserNotSignedIn; } }
/// <summary> /// Sign out of all active accounts associated with this app. /// </summary> public async Task SignOutAsync() { do { var accountsLoaded = await publicClientApplication.GetAccountsAsync(); accounts = accountsLoaded.ToList(); await publicClientApplication.RemoveAsync(accounts.FirstOrDefault()); } while (accounts.Any()); authResult = null; accounts = null; }
public async Task LogoutAsync() { Debug.WriteLine("### LogoutAsync ###"); Session.SetUser(null); while (_accounts.Any()) { await PCA.RemoveAsync(_accounts.FirstOrDefault()); _accounts = await PCA.GetAccountsAsync(); } }