public async Task AuthenticateRequestAsync(HttpRequestMessage request) { AuthenticationResult authResult = null; var accounts = await Application.GetAccountsAsync().ConfigureAwait(true); var firstAccount = accounts.FirstOrDefault(); try { authResult = await Application.AcquireTokenSilent(_scopes, accounts.FirstOrDefault()) .ExecuteAsync().ConfigureAwait(true); } catch (MsalUiRequiredException) { try { await System.Windows.Application.Current.Dispatcher.Invoke <Task>(async() => { authResult = await Application.AcquireTokenInteractive(_scopes) .WithUseEmbeddedWebView(false) .ExecuteAsync().ConfigureAwait(true); }).ConfigureAwait(true); } catch { } } if (authResult != null) { request.Headers.Authorization = new AuthenticationHeaderValue("bearer", authResult.AccessToken); } }
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(""); }
/// <summary> /// Get Token for User. /// </summary> /// <returns>Token for user.</returns> internal static async Task <string> GetTokenForUserAsync(string clientId) { AuthenticationResult authResult; IPublicClientApplication IdentityClientApp = PublicClientApplicationBuilder.Create(clientId).Build(); try { authResult = await IdentityClientApp.AcquireTokenSilent(Scopes, (await IdentityClientApp.GetAccountsAsync()).First()).ExecuteAsync(); TokenForUser = authResult.AccessToken; } catch (Exception) { if (TokenForUser == null || Expiration <= DateTimeOffset.UtcNow.AddMinutes(5)) { authResult = await IdentityClientApp.AcquireTokenInteractive(Scopes).ExecuteAsync(); TokenForUser = authResult.AccessToken; Expiration = authResult.ExpiresOn; } } return(TokenForUser); }
public async Task <string> GetTokenAsync() { string[] scopes = _configuration.GetSection("Scopes").Get <string[]>(); AuthenticationResult authResult; try { IEnumerable <IAccount> accounts = await _clientApp.GetAccountsAsync(); IAccount selectedAccount = accounts.FirstOrDefault(); authResult = selectedAccount == null ? await AcquireTokenInteractive(scopes) : await _clientApp.AcquireTokenSilent(scopes, selectedAccount).ExecuteAsync(); } catch (MsalUiRequiredException) { // A MsalUiRequiredException happened on AcquireTokenSilent. // This indicates you need to call AcquireTokenInteractive to acquire a token authResult = await AcquireTokenInteractive(scopes); } return(authResult.AccessToken); }
// 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 static GraphServiceClient GetAuthenticatedClient(string clientId = TestData.ClientOrAppId) { if (graphClient == null) { TestAuthenticationHelper.clientId = clientId; IdentityClientApp = PublicClientApplicationBuilder.Create(clientId).Build();//https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/wiki/Acquiring-tokens-interactively var accounts = IdentityClientApp.GetAccountsAsync().Result; AuthenticationResult result; try { result = IdentityClientApp.AcquireTokenSilent(Scopes, accounts.FirstOrDefault()) .ExecuteAsync().Result; } catch (MsalUiRequiredException) { result = IdentityClientApp.AcquireTokenInteractive(Scopes) .ExecuteAsync().Result; } graphClient = AuthenticationHelper.GetAuthenticatedClient(result.AccessToken); } return(graphClient); }
public async Task <string> AuthenticateSilent() { _ClientApp = Microsoft.Identity.Client.PublicClientApplicationBuilder .Create(_ViewModel.AuthData.ClientID) .WithAuthority($"{_Instance}{_ViewModel.AuthData.TenantID}") .WithRedirectUri(_ViewModel.AuthData.RedirectURI) .Build(); TokenCacheHelper.EnableSerialization(_ClientApp.UserTokenCache); AuthenticationResult authResult; string result = null; var accounts = await _ClientApp.GetAccountsAsync(); if (accounts.ToList().Count > 0) { var firstAccount = accounts.FirstOrDefault(); try { authResult = await _ClientApp.AcquireTokenSilent(_Scopes, firstAccount) .WithAuthority($"{_Instance}{_ViewModel.AuthData.TenantID}") .ExecuteAsync(); IsConnected = true; result = authResult?.AccessToken; } catch (MsalException msalex) { result = $"Error Acquiring Token:{System.Environment.NewLine}{msalex.Message}"; } } return(result); }
/// <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(); GraphServiceClient = graphClientFactory.CreateClient(authResult); } catch (MsalClientException ex) { if (ex.ErrorCode == ERROR_CODE_CANCELED) { logManager.Info(ex); throw new BackupOperationCanceledException(); } logManager.Error(ex); throw; } }
public async Task <string> GetAccessToken2() { if (_userAccount == null) { try { var result = await _msalClient.AcquireTokenInteractive(_scopes).ExecuteAsync(); _userAccount = result.Account; return(result.AccessToken); } catch (Exception exception) { Console.WriteLine($"Error getting access token: {exception.Message}"); return(null); } } else { // If there is an account, call AcquireTokenSilent // By doing this, MSAL will refresh the token automatically if // it is expired. Otherwise it returns the cached token. var result = await _msalClient .AcquireTokenSilent(_scopes, _userAccount) .ExecuteAsync(); return(result.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); }
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); }
public async Task <bool> AcquireTokenSilentAsync() { try { if (_integratedAuthAvailable) { _authenticationResult = await _client.AcquireTokenByIntegratedWindowsAuth(_scopes) .ExecuteAsync(); } else { var accounts = await _client.GetAccountsAsync(); _authenticationResult = await _client.AcquireTokenSilent(_scopes) .WithAccount(accounts.FirstOrDefault()) .ExecuteAsync(); } return(true); } catch (MsalUiRequiredException) { // Interactive authentication is required return(false); } catch (MsalException) { // TODO WTS: Silentauth failed, please handle this exception as appropriate to your scenario // For more info on MsalExceptions see // https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/wiki/exceptions return(false); } }
public async Task NullAccount_EmptyLoginHintAsync() { IPublicClientApplication app = PublicClientApplicationBuilder .Create(TestConstants.ClientId) .WithTelemetry(new TraceTelemetryConfig()) .Build(); await AssertException.TaskThrowsAsync <ArgumentNullException>( () => app.AcquireTokenSilent(TestConstants.s_scope.ToArray(), (string)null).ExecuteAsync()).ConfigureAwait(false); var ex = await AssertException.TaskThrowsAsync <MsalUiRequiredException>( () => app.AcquireTokenSilent(TestConstants.s_scope.ToArray(), (IAccount)null).ExecuteAsync()).ConfigureAwait(false); Assert.AreEqual(MsalError.UserNullError, ex.ErrorCode); Assert.AreEqual(UiRequiredExceptionClassification.AcquireTokenSilentFailed, ex.Classification); }
public async Task <string> GetAccessToken() { // If there is no saved user account, the user must sign-in if (_userAccount == null) { try { // Invoke device code flow so user can sign-in with a browser var result = await _msalClient.AcquireTokenWithDeviceCode(_scopes, callback => { Console.WriteLine(callback.Message); return(Task.FromResult(0)); }).ExecuteAsync(); _userAccount = result.Account; return(result.AccessToken); } catch (Exception exception) { Console.WriteLine($"Error getting access token: {exception.Message}"); return(null); } } else { // If there is an account, call AcquireTokenSilent // By doing this, MSAL will refresh the token automatically if // it is expired. Otherwise it returns the cached token. var result = await _msalClient .AcquireTokenSilent(_scopes, _userAccount) .ExecuteAsync(); return(result.AccessToken); } }
private async void OutlookRefresh_Click(object sender, RoutedEventArgs e) { try { if (_accessToken == null || _account == null) { statusLabel.Content = "Nothing to refresh. Please sign in first."; return; } statusLabel.Content = "Refreshing..."; // authenticate silently for the scopes we need (refreshing the token if needed) AuthenticationResult result = await _publicClientApplication.AcquireTokenSilent(Scopes, _account).ExecuteAsync(); // update the access token _accessToken = result.AccessToken; // retrieve the list of recent messages await GetMessageListAsync(); } catch (Exception ex) { statusLabel.Content = "Failure."; MessageBox.Show(this, ex.ToString(), "Error"); } }
/// <summary> /// Authenticate and get access token for onedrive /// </summary> /// <returns></returns> public async Task GetToken() { AuthenticationResult authResult = null; IEnumerable <IAccount> accounts = await PCA.GetAccountsAsync(); try { IAccount firstAccount = accounts.FirstOrDefault(); authResult = await PCA.AcquireTokenSilent(Scopes, firstAccount) .ExecuteAsync(); } catch (MsalUiRequiredException ex) { try { authResult = await PCA.AcquireTokenInteractive(Scopes).WithParentActivityOrWindow(App.ParentWindow).ExecuteAsync(); } catch (Exception ex2) { } } GraphClient = new GraphServiceClient(new DelegateAuthenticationProvider( async(request) => { // Add the access token to the "Authorization" header request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken); } )); }
/// <summary> /// Gets an access token. /// </summary> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The access token.</returns> public async Task <string> GetAccessToken(CancellationToken cancellationToken = default) { AuthenticationResult authResult; // let's see if we have the user details already available. try { authResult = await AuthenticationClient.AcquireTokenSilent(AuthenticationConfig.Scopes).ExecuteAsync(cancellationToken).ConfigureAwait(false); } catch (AuthUiRequiredException) { try { authResult = await AuthenticationClient.AcquireTokenInteractive(AuthenticationConfig.Scopes) .WithParentActivityOrWindow(App.ParentWindow) .ExecuteAsync(cancellationToken) .ConfigureAwait(false); } catch (Exception ex) { this.Log().Warn(ex, "Could not log into the authentication system"); return(null !); } } return(authResult.AccessToken); }
private async Task Init(bool isAppStarting) { var accounts = (await _app.GetAccountsAsync()).ToList(); if (!accounts.Any()) { SignInButton.Content = SignInString; return; } AuthenticationResult result = null; try { result = await _app.AcquireTokenSilent(Scopes, accounts.FirstOrDefault()) .ExecuteAsync() .ConfigureAwait(false); Dispatcher.Invoke( () => { SignInButton.Content = ClearCacheString; SetUserName(result.Account); }); } // There is no access token in the cache, so prompt the user to sign-in. catch (MsalUiRequiredException) { if (!isAppStarting) { SignInButton.Content = SignInString; } } 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); UserName.Content = FilesApplication.Resources.UserNotSignedIn; return; } }
public bool CreatePublicClient(bool prompt, bool deviceLogin = false) { Log.Info($"enter: {prompt} {deviceLogin}"); _publicClientApp = PublicClientApplicationBuilder .Create(_wellKnownClientId) .WithAuthority(AzureCloudInstance.AzurePublic, Config.AzureTenantId) .WithLogging(MsalLoggerCallback, LogLevel.Verbose, true, true) .WithDefaultRedirectUri() .Build(); if (_instance.IsWindows) { TokenCacheHelper.EnableSerialization(_publicClientApp.UserTokenCache); } if (prompt) { if (deviceLogin) { AuthenticationResult = _publicClientApp .AcquireTokenWithDeviceCode(_defaultScope, MsalDeviceCodeCallback) .ExecuteAsync().Result; } else { AuthenticationResult = _publicClientApp .AcquireTokenInteractive(_defaultScope) .ExecuteAsync().Result; } } else { AuthenticationResult = _publicClientApp .AcquireTokenSilent(_defaultScope, _publicClientApp.GetAccountsAsync().Result.FirstOrDefault()) .ExecuteAsync().Result; } if (Scopes.Count > 0) { Log.Info($"adding scopes {Scopes.Count}"); AuthenticationResult = _publicClientApp .AcquireTokenSilent(Scopes, _publicClientApp.GetAccountsAsync().Result.FirstOrDefault()) .ExecuteAsync().Result; } return(true); }
private async Task <string> TryLoginSilent(string iocPath) { IAccount account = null; try { if (IsConnected(iocPath)) { return(iocPath); } String userId = OneDrive2ItemLocation <OneDrive2PrefixContainerType> .FromString(iocPath).User?.Id; logDebug("needs acquire token"); logDebug("trying silent login " + iocPath); account = Task.Run(async() => await _publicClientApp.GetAccountAsync(userId)).Result; logDebug("getting user ok."); } catch (Exception e) { logDebug(e.ToString()); } if (account != null) { try { logDebug("AcquireTokenSilent..."); AuthenticationResult authResult = await _publicClientApp.AcquireTokenSilent(Scopes, account) .ExecuteAsync(); logDebug("AcquireTokenSilent ok."); BuildClient(authResult); /*User me = await graphClient.Me.Request().WithForceRefresh(true).GetAsync(); * logDebug("received name " + me.DisplayName);*/ return(BuildRootPathForUser(authResult)); } catch (MsalUiRequiredException ex) { GraphServiceClientWithState clientWithState = new GraphServiceClientWithState() { Client = null, RequiresUserInteraction = true }; mClientByUser[account.HomeAccountId.Identifier] = clientWithState; logDebug("ui required"); return(null); } catch (Exception ex) { logDebug("silent login failed: " + ex.ToString()); return(null); } } return(null); }
public bool CreatePublicClient(bool prompt, bool deviceLogin = false) { Log.Info($"enter: {prompt} {deviceLogin}"); AuthenticationResult result = null; _publicClientApp = PublicClientApplicationBuilder .Create(_wellKnownClientId) .WithAuthority(AzureCloudInstance.AzurePublic, _config.AzureTenantId) .WithLogging(MsalLoggerCallback, LogLevel.Verbose, true, true) .WithDefaultRedirectUri() .Build(); TokenCacheHelper.EnableSerialization(_publicClientApp.UserTokenCache); if (prompt) { if (deviceLogin) { result = _publicClientApp.AcquireTokenWithDeviceCode(_defaultScope, MsalDeviceCodeCallback).ExecuteAsync().Result; } else { result = _publicClientApp.AcquireTokenInteractive(_defaultScope).ExecuteAsync().Result; } } else { IAccount hint = _publicClientApp.GetAccountsAsync().Result.FirstOrDefault(); if (hint == null && !TokenCacheHelper.HasTokens) { throw new MsalUiRequiredException("unable to acquire token silently.", "no hint and no cached tokens."); } result = _publicClientApp.AcquireTokenSilent(_defaultScope, hint).ExecuteAsync().Result; } if (Scopes.Count > 0) { Log.Info($"adding scopes {Scopes.Count}"); result = _publicClientApp.AcquireTokenSilent(Scopes, _publicClientApp.GetAccountsAsync().Result.FirstOrDefault()).ExecuteAsync().Result; } AuthenticationResultToken = new AccessToken(result.AccessToken, result.ExpiresOn); return(true); }
/// <inheritdoc /> public async Task <IToken> GetTokenAsync(IEnumerable <string> scopes, CancellationToken cancel = default) { Log(Microsoft.Extensions.Logging.LogLevel.Information, "checking for accounts in shared developer tool cache"); var accounts = (await GetAccountsAsync().ConfigureAwait(false)).ToList(); if (!accounts.Any()) { throw new InvalidOperationException("there are no accounts available to acquire a token"); } var res = await _app.AcquireTokenSilent(scopes, accounts.First()) .ExecuteAsync(cancel) .ConfigureAwait(false); return(new AccessTokenWithExpiration { ExpiresOn = res.ExpiresOn, AccessToken = res.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 SignIn() { // First, attempt silent sign in // If the user's information is already in the App's cache, // they won't have to sign in again. try { if (PCA == null) { InitInstance(); } var accounts = await PCA.GetAccountsAsync(); var silentAuthResult = await PCA .AcquireTokenSilent(Scopes, accounts.FirstOrDefault()) .ExecuteAsync(); LogManager.GetCurrentClassLogger().Info($"Successful silent authentication for: {silentAuthResult.Account.Username}"); } catch (MsalUiRequiredException msalEx) { // This exception is thrown when an interactive sign-in is required. LogManager.GetCurrentClassLogger().Warn(msalEx); // Prompt the user to sign-in var interactiveRequest = PCA.AcquireTokenInteractive(Scopes); if (AuthUIParent != null) { interactiveRequest = interactiveRequest .WithParentActivityOrWindow(AuthUIParent); } var interactiveAuthResult = await interactiveRequest.ExecuteAsync(); LogManager.GetCurrentClassLogger().Info($"Successful interactive authentication for: {interactiveAuthResult.Account.Username}"); } catch (Exception ex) { LogManager.GetCurrentClassLogger().Error(ex); } await InitializeGraphClientAsync(); }
public static async Task <string> GetTokenForUserAsync() { //AuthenticationContext ADALIdentityClientApp = new AuthenticationContext(authority + // Properties.Settings.Default.TenantId); AuthenticationResult authResult; authority = string.Format(CultureInfo.InvariantCulture, authority, Properties.Settings.Default.TenantId); if (_app == null) { _app = PublicClientApplicationBuilder.Create(Properties.Settings.Default.V2AppId) .WithAuthority(authority) .WithRedirectUri("https://b2capi.com") .Build(); TokenCacheHelper.EnableSerialization(_app.UserTokenCache); } var accounts = (await _app.GetAccountsAsync()).ToList(); string tokenForUser = null; try { authResult = await _app.AcquireTokenSilent(Scopes, accounts.FirstOrDefault()) .ExecuteAsync() .ConfigureAwait(false); //authResult = await ADALIdentityClientApp.AcquireTokenAsync("https://graph.microsoft.com", Properties.Settings.Default.V2AppId, new Uri("https://b2capi.com"), new PlatformParameters(PromptBehavior.Auto)); //authResult = await ADALIdentityClientApp.AcquireTokenSilentAsync(Scopes, ADALIdentityClientApp.Users.First()); tokenForUser = authResult.AccessToken; } catch (MsalUiRequiredException) { //if (tokenForUser == null || Expiration <= DateTimeOffset.UtcNow.AddMinutes(5)) //{ try { //authResult = await ADALIdentityClientApp.AcquireTokenAsync("https://graph.microsoft.com", Properties.Settings.Default.V2AppId, new Uri("https://b2capi.com"), new PlatformParameters(PromptBehavior.Auto)); authResult = await _app.AcquireTokenInteractive(Scopes) .WithAccount(accounts.FirstOrDefault()) .WithPrompt(Prompt.SelectAccount) .ExecuteAsync() .ConfigureAwait(false); tokenForUser = authResult.AccessToken; //Expiration = authResult.ExpiresOn; } catch { return(tokenForUser); } //} } return(tokenForUser); }
private async Task <string> Refresh() { var accounts = await Client.GetAccountsAsync(); var account = accounts.First(); var tokens = await Client.AcquireTokenSilent(new string[] { "openid" }, account).ExecuteAsync(); return(tokens.IdToken); }
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); } }
// </AppConstructorSnippet> public async Task SignIn() { // <GetTokenSnippet> // First, attempt silent sign in // If the user's information is already in the app's cache, // they won't have to sign in again. try { var accounts = await PCA.GetAccountsAsync(); var silentAuthResult = await PCA .AcquireTokenSilent(Scopes, accounts.FirstOrDefault()) .ExecuteAsync(); Debug.WriteLine("User already signed in."); Debug.WriteLine($"Successful silent authentication for: {silentAuthResult.Account.Username}"); Debug.WriteLine($"Access token: {silentAuthResult.AccessToken}"); } catch (MsalUiRequiredException msalEx) { // This exception is thrown when an interactive sign-in is required. Debug.WriteLine("Silent token request failed, user needs to sign-in: " + msalEx.Message); // Prompt the user to sign-in var interactiveRequest = PCA.AcquireTokenInteractive(Scopes); if (AuthUIParent != null) { interactiveRequest = interactiveRequest .WithParentActivityOrWindow(AuthUIParent); } var interactiveAuthResult = await interactiveRequest.ExecuteAsync(); Debug.WriteLine($"Successful interactive authentication for: {interactiveAuthResult.Account.Username}"); Debug.WriteLine($"Access token: {interactiveAuthResult.AccessToken}"); } catch (Exception ex) { Debug.WriteLine("Authentication failed. See exception messsage for more details: " + ex.Message); } // </GetTokenSnippet> await InitializeGraphClientAsync(); }
private async Task <AuthenticationResult> RunAtsAsync(IPublicClientApplication pca) { string reqAuthority = pca.Authority; string loginHint = GetLoginHint(); if (!string.IsNullOrEmpty(loginHint) && cbxAccount.SelectedIndex > 0) { throw new InvalidOperationException("[TEST APP FAILURE] Please use either the login hint or the account"); } if (!string.IsNullOrEmpty(loginHint)) { if (IsMsaPassthroughConfigured()) { throw new InvalidAsynchronousStateException( "[TEST APP FAILURE] Do not use login hint on AcquireTokenSilent for MSA-Passthrough. Use the IAccount overload."); } Log($"ATS with login hint: " + loginHint); return(await pca.AcquireTokenSilent(GetScopes(), loginHint) .ExecuteAsync() .ConfigureAwait(false)); } if (cbxAccount.SelectedItem != null && (cbxAccount.SelectedItem as AccountModel).Account != s_nullAccount) { var acc = (cbxAccount.SelectedItem as AccountModel).Account; Log($"ATS with IAccount for {acc?.Username ?? acc.HomeAccountId.ToString() ?? "null"}"); return(await pca.AcquireTokenSilent(GetScopes(), acc) .WithAuthority(reqAuthority) .ExecuteAsync() .ConfigureAwait(false)); } Log($"ATS with no account or login hint ... will fail with UiRequiredEx"); return(await pca.AcquireTokenSilent(GetScopes(), (IAccount)null) .ExecuteAsync() .ConfigureAwait(false)); }
public async Task <bool> SignInSilentAsync() { try { var accounts = await _pca.GetAccountsAsync(); var firstAccount = accounts.FirstOrDefault(); var authResult = await _pca.AcquireTokenSilent(Constants.AuthScopes, firstAccount).ExecuteAsync(); // Store the access token securely for later use. await SecureStorage.SetAsync("AccessToken", $"{Constants.AuthType} {authResult?.AccessToken}"); return(true); } catch (MsalUiRequiredException) { return(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); }