private async Task AcquireTokenSilentAsync() { try { AcquireTokenInteractiveParameterBuilder request = PublicClientApplication.AcquireTokenInteractive(App.s_defaultScopes) .WithPrompt(Prompt.ForceLogin) .WithParentActivityOrWindow(App.RootViewController); //.WithUseEmbeddedWebView(true); AuthenticationResult result = await request.ExecuteAsync().ConfigureAwait(true); AcquireTokenSilentParameterBuilder builder = PublicClientApplication.AcquireTokenSilent( App.s_defaultScopes, result.Account.Username); AuthenticationResult res = await builder .WithForceRefresh(false) .ExecuteAsync() .ConfigureAwait(true); var resText = GetResultDescription(res); if (res.AccessToken != null) { acquireResponseTitleLabel.Text = SuccessfulResult; } acquireResponseLabel.Text = "Acquire Token Silent Acquisition Result....\n" + resText; } catch (Exception exception) { CreateExceptionMessage(exception); } }
/// <summary> /// Instructs AAD to return an SSH certificate instead of a Bearer token. Attempts to retrieve /// the certificate from the token cache, and if one is not found, attempts to acquire one silently, /// using the refresh token. See https://aka.ms/msal-net-ssh for details. /// </summary> /// <remarks> /// The same keyID must be used to distinguish between various /// </remarks> /// <param name="builder">Silent authentication builder</param> /// <param name="publicKeyJwk">The public SSH key in JWK format (https://tools.ietf.org/html/rfc7517). /// Currently only RSA is supported, and the JWK should contain only the RSA modulus and exponent</param> /// <param name="keyId"></param> /// <returns></returns> public static AcquireTokenSilentParameterBuilder WithSSHCertificateAuthenticationScheme( this AcquireTokenSilentParameterBuilder builder, string publicKeyJwk, string keyId) { builder.CommonParameters.AuthenticationScheme = new SSHCertAuthenticationScheme(keyId, publicKeyJwk); return(builder); }
/// <summary> /// Attempts to acquire access token silently from the token cache. /// </summary> /// <exception cref="AuthenticationException">An exception occured when attempting to get access token silently.</exception> internal static async Task <AuthenticationResult> GetAccessTokenSilentAsync(this IClientApplicationBase clientApplication, AuthenticationProviderOption msalAuthProviderOption) { IAccount account; if (msalAuthProviderOption.UserAccount?.ObjectId != null) { // Parse GraphUserAccount to IAccount instance account = new GraphAccount(msalAuthProviderOption.UserAccount); } else { // If no graph user account is passed, try get the one in cache. IEnumerable <IAccount> accounts = await clientApplication.GetAccountsAsync(); account = accounts.FirstOrDefault(); } if (account == null) { return(null); } try { AcquireTokenSilentParameterBuilder tokenSilentBuilder = clientApplication.AcquireTokenSilent(msalAuthProviderOption.Scopes, account) .WithForceRefresh(msalAuthProviderOption.ForceRefresh); if (!ContainsWellKnownTenantName(clientApplication.Authority)) { tokenSilentBuilder.WithAuthority(clientApplication.Authority); } if (!string.IsNullOrEmpty(msalAuthProviderOption.Claims)) { tokenSilentBuilder.WithClaims(msalAuthProviderOption.Claims); } return(await tokenSilentBuilder.ExecuteAsync()); } catch (MsalException) { return(null); } catch (Exception exception) { throw new AuthenticationException( new Error { Code = ErrorConstants.Codes.GeneralException, Message = ErrorConstants.Message.UnexpectedException }, exception); } }
private async Task <(HttpRequestMessage HttpRequest, Guid Correlationid)> RunAcquireTokenSilentAsync( AcquireTokenSilentOutcome outcome, bool forceRefresh = false) { MockHttpMessageHandler tokenRequest = null; Guid correlationId = Guid.Empty; var account = (await _app.GetAccountsAsync().ConfigureAwait(false)).Single(); AcquireTokenSilentParameterBuilder request = _app .AcquireTokenSilent(TestConstants.s_scope, account) .WithForceRefresh(forceRefresh); switch (outcome) { case AcquireTokenSilentOutcome.SuccessFromCache: var authResult = await request .ExecuteAsync() .ConfigureAwait(false); correlationId = authResult.CorrelationId; break; case AcquireTokenSilentOutcome.SuccessViaRefreshGrant: // let's remove the AT so that they can't be used _app.UserTokenCacheInternal.Accessor.ClearAccessTokens(); tokenRequest = _harness.HttpManager.AddSuccessTokenResponseMockHandlerForPost(TestConstants.AuthorityUtidTenant); authResult = await request .ExecuteAsync() .ConfigureAwait(false); correlationId = authResult.CorrelationId; break; case AcquireTokenSilentOutcome.FailInvalidGrant: (tokenRequest, correlationId) = await RunSilentFlowWithTokenErrorAsync(request, "invalid_grant") .ConfigureAwait(false); break; case AcquireTokenSilentOutcome.FailInteractionRequired: (tokenRequest, correlationId) = await RunSilentFlowWithTokenErrorAsync(request, "interaction_required") .ConfigureAwait(false); break; default: throw new NotImplementedException(); } Assert.AreEqual(0, _harness.HttpManager.QueueSize); return(tokenRequest?.ActualRequestMessage, correlationId); }
private async Task AcquireTokenSilentAsync() { try { Console.WriteLine("[TESTLOG] - start AcquireTokenSilentAsync"); Console.WriteLine($"[TESTLOG] - PublicClientApplication? {_publicClientApplication == null}"); AcquireTokenInteractiveParameterBuilder request = _publicClientApplication.AcquireTokenInteractive(new[] { "user.read" }) .WithPrompt(Prompt.ForceLogin) .WithUseEmbeddedWebView(true); Console.WriteLine("[TESTLOG] - WithParentActivityOrWindow"); Console.WriteLine($"[TESTLOG] - WithParentActivityOrWindow - root view controller {App.RootViewController}"); request.WithParentActivityOrWindow(App.RootViewController); Console.WriteLine("[TESTLOG] - after creating request"); AuthenticationResult result = await request.ExecuteAsync().ConfigureAwait(true); Console.WriteLine("[TESTLOG] - after executing interactive request"); AcquireTokenSilentParameterBuilder builder = _publicClientApplication.AcquireTokenSilent( App.s_scopes, result.Account.Username); Console.WriteLine("[TESTLOG] - after creating silent request"); AuthenticationResult res = await builder .WithForceRefresh(false) .ExecuteAsync() .ConfigureAwait(true); Console.WriteLine("[TESTLOG] - after executing silent request"); var resText = GetResultDescription(res); if (res.AccessToken != null) { acquireResponseTitleLabel.Text = SuccessfulResult; } acquireResponseLabel.Text = "Acquire Token Silent Acquisition Result....\n" + resText; } catch (Exception exception) { CreateExceptionMessage(exception); } }
private async Task <(MockHttpMessageHandler MockHttpHandler, Guid Correlationid)> RunSilentFlowWithTokenErrorAsync(AcquireTokenSilentParameterBuilder request, string errorCode) { _app.UserTokenCacheInternal.Accessor.ClearAccessTokens(); var correlationId = Guid.NewGuid(); var tokenRequest = _harness.HttpManager.AddFailureTokenEndpointResponse( errorCode, TestConstants.AuthorityUtidTenant, correlationId.ToString()); var ex = await AssertException.TaskThrowsAsync <MsalServiceException>( () => request.WithCorrelationId(correlationId).ExecuteAsync(), allowDerived : true) .ConfigureAwait(false); Assert.AreEqual( correlationId, Guid.Parse(ex.CorrelationId), "Test error - Exception correlation ID does not match WithCorrelationId value"); return(tokenRequest, correlationId); }