private async Task <AuthResult> AcquireTokenAsync(IPublicClientApplication app, IEnumerable <string> scopes, string usrId) { var acct = !string.IsNullOrEmpty(usrId) ? await app.GetAccountAsync(usrId) : null; var userStr = acct != null ? acct.Username : "******"; Debug.Log($"Found User {userStr}"); AuthResult res = new AuthResult(); try { Debug.Log($"Calling AcquireTokenSilentAsync"); res.res = await app.AcquireTokenSilentAsync(scopes, acct).ConfigureAwait(false); Debug.Log($"app.AcquireTokenSilentAsync called {res.res}"); } catch (MsalUiRequiredException) { Debug.Log($"Needs UI for Login"); try { res.res = await app.AcquireTokenAsync(scopes).ConfigureAwait(false); Debug.Log($"app.AcquireTokenAsync called {res.res}"); } catch (MsalException msalex) { res.err = $"Error Acquiring Token:{Environment.NewLine}{msalex.Message}"; Debug.Log($"{res.err}"); return(res); } catch (Exception ex) { res.err = $"Error Acquiring Token Silently:{Environment.NewLine}{ex.Message}"; Debug.Log($"{res.err}"); return(res); } } catch (Exception ex) { res.err = $"Error Acquiring Token Silently:{Environment.NewLine}{ex.Message}"; Debug.Log($"{res.err}"); return(res); } #if !UNITY_EDITOR && UNITY_WSA Debug.Log($"Access Token - {res.res.AccessToken}"); ApplicationData.Current.LocalSettings.Values["UserId"] = res.res.Account.HomeAccountId.Identifier; #endif return(res); }
public async Task <AuthResult> AcquireTokenAsync(IPublicClientApplication app, IEnumerable <string> scopes, string usrId, Func <AuthenticationResult, Task> callback) { var usr = !string.IsNullOrEmpty(usrId) ? await app.GetAccountAsync(usrId) : null; var userStr = usr != null ? usr.Username : "******"; //Debug.Log($"Found User {userStr}"); AuthResult res = new AuthResult(); try { //Debug.Log($"Calling AcquireTokenSilentAsync"); res.res = await app.AcquireTokenSilentAsync(scopes, usr).ConfigureAwait(false); //Debug.Log($"app.AcquireTokenSilentAsync called {res.res}"); } catch (MsalUiRequiredException) { //Debug.Log($"Needs UI for Login"); try { res.res = await app.AcquireTokenAsync(scopes).ConfigureAwait(false); if (callback != null) { await callback(res.res); } //Debug.Log($"app.AcquireTokenAsync called {res.res}"); } catch (MsalException msalex) { res.err = $"Error Acquiring Token:{Environment.NewLine}{msalex}"; //Debug.Log($"{res.err}"); return(res); } } catch (Exception ex) { res.err = $"Error Acquiring Token Silently:{Environment.NewLine}{ex}"; //Debug.Log($"{res.err}"); return(res); } #if !UNITY_EDITOR && UNITY_WSA Debug.Log($"Access Token - {res.res.AccessToken}"); ApplicationData.Current.LocalSettings.Values["UserId"] = res.res.User.Identifier; #endif return(res); }
protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { if (ServerCertificateCustomValidationCallback == null && request.RequestUri.Host == "localhost") { ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true; } var accounts = await _publicClientApplication.GetAccountsAsync(); var result = await _publicClientApplication.AcquireTokenSilentAsync(_scopes, accounts.First()); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken); return(await base.SendAsync(request, cancellationToken)); }
public async Task <string> GetTokenAsync() { try { var ar = await _pca.AcquireTokenSilentAsync(_scopes, GetUserByPolicy(_pca.Users, _policySignUpSignIn), _authority, false); return(ar.AccessToken); } catch (MsalUiRequiredException) { throw new LoginRequestedException(); } catch (Exception) { throw new TokenNotAvailableException(); } }
private static async Task <AuthenticationResult> CreateAuthResult(IPublicClientApplication app) { AuthenticationResult authResult = null; // This opens a browser window and ask for a microsoft account the frist time var accounts = await app.GetAccountsAsync(); try { authResult = await app.AcquireTokenSilentAsync(scopes, accounts.FirstOrDefault()); } catch (MsalUiRequiredException ex) { System.Diagnostics.Debug.WriteLine($"MsalUiRequiredException: {ex.Message}"); try { throw new NotSupportedException("Plase wait microsoft solved the issue https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/issues/728"); // Todo: implement device code flow instead of username and passwort if this isse is solved: https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/issues/728 // we now must use device authentification! authResult = await app.AcquireTokenWithDeviceCodeAsync(scopes, (result) => { Console.WriteLine("Login success with message: " + result.Message); return(Task.FromResult(0)); }, CancellationToken.None); //Console.WriteLine("Input your OneDrive username"); //var user = Console.ReadLine(); //Console.WriteLine("Input your OneDrive passwort"); //var password = GetPassword(); //authResult = await app.AcquireTokenByUsernamePasswordAsync(scopes, user, password); } catch (MsalException msalex) { throw new Exception($"Error Acquiring Token:{System.Environment.NewLine}{msalex}"); } } catch (Exception ex) { throw new Exception($"Error Acquiring Token Silently:{System.Environment.NewLine}{ex}"); } if (authResult != null) { return(authResult); } throw new Exception("Error while creating a token."); }
private async void AccessTokenSilentButton_ClickAsync(object sender, RoutedEventArgs e) { var accounts = await _pca.GetAccountsAsync().ConfigureAwait(false); AuthenticationResult result = null; try { result = await _pca.AcquireTokenSilentAsync(Scopes, accounts.FirstOrDefault()).ConfigureAwait(false); } catch (Exception ex) { await DisplayErrorAsync(ex).ConfigureAwait(false); return; } await DisplayResultAsync(result).ConfigureAwait(false); }
public async Task <bool> AcquireTokenSilently() { try { var accounts = await publicClientApplication.GetAccountsAsync(); var firstAccount = accounts.FirstOrDefault(); var authenticationResult = await publicClientApplication.AcquireTokenSilentAsync(AuthConfig.Scopes, firstAccount); AuthenticationResult = authenticationResult; HandleTokenAcquisition(authenticationResult != null); return(authenticationResult != null); } catch (Exception ex) { logger.Log(ex, "Error acquiring B2C token silently"); } return(false); }
/// <summary> /// Attempt to retrieve the Access Token by either retrieving /// previously stored credentials or by prompting user to Login /// </summary> private async Task <AuthenticationResult> AcquireTokenAsync( IPublicClientApplication app, IEnumerable <string> scopes, string userId) { IUser user = !string.IsNullOrEmpty(userId) ? app.GetUser(userId) : null; string userName = user != null ? user.Name : "null"; // Once the User name is found, display it as a welcome message MeetingsUI.Instance.WelcomeUser(userName); // Attempt to Log In the user with a pre-stored token. Only happens // in case the user Logged In with this app on this device previously try { _authResult = await app.AcquireTokenSilentAsync(scopes, user); } catch (MsalUiRequiredException) { // Pre-stored token not found, prompt the user to log-in try { _authResult = await app.AcquireTokenAsync(scopes); } catch (MsalException msalex) { Debug.Log($"Error Acquiring Token: {msalex.Message}"); return(_authResult); } } MeetingsUI.Instance.WelcomeUser(_authResult.User.Name); #if !UNITY_EDITOR && UNITY_WSA ApplicationData.Current.LocalSettings.Values["UserId"] = _authResult.User.Identifier; #endif return(_authResult); }