/// <summary>
        /// When the Web API needs consent, it can sent a 403 with information in the WWW-Authenticate header in
        /// order to challenge the user
        /// </summary>
        /// <param name="response">HttpResonse received from the service</param>
        /// <returns></returns>
        private async Task HandleChallengeFromWebApi(HttpResponseMessage response, IAccount account)
        {
            WwwAuthenticateParameters wwwAuthenticateParameters = WwwAuthenticateParameters.CreateFromResponseHeaders(response.Headers);
            string claims         = wwwAuthenticateParameters.Claims;
            string proposedAction = wwwAuthenticateParameters["proposedAction"];
            string consentUri     = wwwAuthenticateParameters["consentUri"];

            string loginHint            = account?.Username;
            string domainHint           = IsConsumerAccount(account) ? "consumers" : "organizations";
            string extraQueryParameters = $"claims={claims}&domainHint={domainHint}";

            if (proposedAction == "forceRefresh")
            {
                // Removes the account, but then re-signs-in
                await _app.RemoveAsync(account);

                await _app.AcquireTokenInteractive(new string[] { "user.read" })
                .WithPrompt(Prompt.Consent)
                .WithLoginHint(loginHint)
                .WithExtraQueryParameters(extraQueryParameters)
                .WithAuthority(_app.Authority)
                .ExecuteAsync()
                .ConfigureAwait(false);
            }
            else if (proposedAction == "consent")
            {
                if (System.Windows.MessageBox.Show("You need to consent to the Web API. If you press Ok, you'll be redirected to a browser page to consent",
                                                   "Consent needed for the Web API",
                                                   MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                {
                    Process.Start(consentUri);
                }
            }
        }
Exemple #2
0
        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);
            }
        }
        private async Task AcquireTokenInteractiveAsync(Prompt prompt)
        {
            try
            {
                AcquireTokenInteractiveParameterBuilder request = _publicClientApplication.AcquireTokenInteractive(App.s_scopes)
                                                                  .WithPrompt(prompt)
                                                                  .WithParentActivityOrWindow(App.RootViewController)
                                                                  .WithUseEmbeddedWebView(true);

                AuthenticationResult result = await
                                              request.ExecuteAsync().ConfigureAwait(true);

                var resText = GetResultDescription(result);

                if (result.AccessToken != null)
                {
                    acquireResponseTitleLabel.Text = SuccessfulResult;
                }

                acquireResponseLabel.Text = resText;
            }
            catch (Exception exception)
            {
                CreateExceptionMessage(exception);
            }
        }
Exemple #4
0
        private async Task <IUserContext> SignInInteractively(IAccount account, CancellationToken ct)
        {
            try
            {
                IsInterativeSignInInProgress = true;

                AuthenticationResult authResult;

                if (account is null)
                {
                    authResult = await _pca.AcquireTokenInteractive(_defaultScopes)
                                 .ExecuteAsync(ct);
                }
                else
                {
                    authResult = await _pca.AcquireTokenInteractive(_defaultScopes)
                                 .WithAccount(account)
                                 .ExecuteAsync(ct);
                }

                return(new UserContext(authResult));
            }
            catch (Exception ex)
            {
                throw new B2CAuthClientException($"Unable to acquire token interactive. Unhandled exception: {ex}");
            }
            finally
            {
                IsInterativeSignInInProgress = false;
            }
        }
        private async Task <string> GetAccessToken(string[] scopes)
        {
            var accounts = await _clientApp.GetAccountsAsync();

            var firstAccount = accounts.FirstOrDefault();
            AuthenticationResult authResult = null;

            try
            {
                authResult = await _clientApp.AcquireTokenSilent(scopes, firstAccount)
                             .ExecuteAsync()
                             .ConfigureAwait(false);
            }
            catch (MsalUiRequiredException ex)
            {
                // A MsalUiRequiredException happened on AcquireTokenSilent.
                // This indicates you need to call AcquireTokenInteractive to acquire a token
                System.Diagnostics.Debug.WriteLine($"MsalUiRequiredException: {ex.Message}");

                try
                {
                    authResult = await _clientApp.AcquireTokenInteractive(scopes)
                                 .WithClaims(ex.Claims)
                                 .WithAccount(firstAccount)
                                 .ExecuteAsync()
                                 .ConfigureAwait(false);
                }
                catch (MsalException msalex)
                {
                    System.Diagnostics.Debug.WriteLine("Error Acquiring Token: " + msalex.Message);
                    return(null);
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("Error Acquiring Token Silently: " + ex.Message);
                return(null);
            }

            if (null != authResult)
            {
                await Dispatcher.BeginInvoke((Action)(() =>
                {
                    DisplayIDToken(authResult);
                    DisplayBasicTokenResponseInfo(authResult);
                }));

                return(authResult.AccessToken);
            }
            else
            {
                return(null);
            }
        }
Exemple #6
0
        public async Task <UserContext> ResetPasswordAsync()
        {
            AuthenticationResult authResult = await _pca.AcquireTokenInteractive(B2CConstants.Scopes)
                                              .WithPrompt(Prompt.NoPrompt)
                                              .WithAuthority(B2CConstants.AuthorityPasswordReset)
                                              .ExecuteAsync();

            var userContext = UpdateUserInfo(authResult);

            return(userContext);
        }
        private async Task <UserContext> SignInInteractively()
        {
            IEnumerable <IAccount> accounts = await _pca.GetAccountsAsync();

            AuthenticationResult authResult = await _pca.AcquireTokenInteractive(Scopes)
                                              .WithAccount(GetAccountByPolicy(accounts, PolicySignUpSignIn))
                                              .ExecuteAsync();

            var newContext = UpdateUserInfo(authResult);

            return(newContext);
        }
Exemple #8
0
        public async Task <UserContext> ResetPasswordAsync()
        {
            AuthenticationResult ar = await PCA.AcquireTokenInteractive(B2CConstants.Scopes)
                                      .WithPrompt(Prompt.NoPrompt)
                                      .WithAuthority(B2CConstants.AuthorityPasswordReset)
                                      .WithParentActivityOrWindow(ParentActivityOrWindow)
                                      .ExecuteAsync();

            var userContext = UpdateUserInfo(ar);

            this.userContext = userContext;
            return(userContext);
        }
Exemple #9
0
        public async Task AuthenticateRequestAsync(HttpRequestMessage request)
        {
            AuthenticationResult authResult = null;

            var accounts = await Application.GetAccountsAsync();

            var firstAccount = accounts.FirstOrDefault();

            try
            {
                authResult = await Application.AcquireTokenSilent(_scopes, accounts.FirstOrDefault())
                             .ExecuteAsync();
            }
            catch (MsalUiRequiredException)
            {
                try
                {
                    await System.Windows.Application.Current.Dispatcher.Invoke <Task>(async() =>
                    {
                        authResult = await Application.AcquireTokenInteractive(_scopes)
                                     .WithUseEmbeddedWebView(false)
                                     .ExecuteAsync();
                    });
                }
                catch
                {
                }
            }

            if (authResult != null)
            {
                request.Headers.Authorization = new AuthenticationHeaderValue("bearer", authResult.AccessToken);
            }
        }
Exemple #10
0
    public async Task LoginAsync()
    {
        try
        {
            string[] scopes       = { "user.read" };
            string[] webApiScopes = { "https://procsharp.onmicrosoft.com/booksservices/Books.Read" };
            var      accounts     = await _clientAuthApp.GetAccountsAsync(_signinPolicyId);

            var firstAccount = accounts.FirstOrDefault();
            AuthenticationResult?result;
            if (firstAccount is not null)
            {
                result = await _clientAuthApp.AcquireTokenSilent(scopes, firstAccount)
                         .ExecuteAsync();
            }
            else
            {
                result = await _clientAuthApp.AcquireTokenInteractive(scopes)
                         .WithExtraScopesToConsent(webApiScopes)
                         .ExecuteAsync();
            }

            _logger.LogTrace("$logged in with {0}", result.Account.Username);
            _accessToken = result.AccessToken;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, ex.Message);
            throw;
        }
    }
Exemple #11
0
        /// <summary>
        /// Force to signin the user in an interactive authentication flow.
        /// </summary>
        /// <returns></returns>
        public async Task ForceInteractiveSignIn()
        {
            try
            {
                OnAuthenticationChanged?.Invoke(this, AuthenticationState.StartedInteractive);
                var authResult = await identityClientApp.AcquireTokenInteractive(grantScopes).ExecuteAsync();

                // Set access token and expiration
                TokenForUser = authResult.AccessToken;
                Expiration   = authResult.ExpiresOn;

                OnAuthenticationChanged?.Invoke(this, AuthenticationState.Completed);
            }
            catch (Exception e) when(e is PlatformNotSupportedException || e is MsalUiRequiredException)
            {
                var authResult = await identityClientApp.AcquireTokenWithDeviceCode(grantScopes, dcr =>
                {
                    OnAuthenticationChanged?.Invoke(this, AuthenticationState.FallbackToDeviceCode);
                    OnPresentDeviceCode?.Invoke(this, dcr);
                    return(Task.FromResult(0));
                }).ExecuteAsync();

                // Set access token and expiration
                TokenForUser = authResult.AccessToken;
                Expiration   = authResult.ExpiresOn;
                OnAuthenticationChanged?.Invoke(this, AuthenticationState.Completed);
            }
            catch (Exception)
            {
                OnAuthenticationChanged?.Invoke(this, AuthenticationState.Failed);
            }
        }
Exemple #12
0
        /// <summary>
        /// Get Token for User.
        /// </summary>
        /// <returns>Token for user.</returns>
        public static async Task <string> GetTokenForUserAsync()
        {
            AuthenticationResult authResult;

            // 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.
            try
            {
                authResult = await IdentityClientApp.AcquireTokenSilent(Scopes, (await IdentityClientApp.GetAccountsAsync()).FirstOrDefault()).ExecuteAsync().ConfigureAwait(false);

                _tokenForUser = authResult.AccessToken;
            }
            catch (Exception)
            {
                if (_tokenForUser == null || _expiration <= DateTimeOffset.UtcNow.AddMinutes(5))
                {
                    authResult = await IdentityClientApp.AcquireTokenInteractive(Scopes).ExecuteAsync().ConfigureAwait(false);

                    _tokenForUser = authResult.AccessToken;
                    _expiration   = authResult.ExpiresOn;
                }
            }

            return(_tokenForUser);
        }
Exemple #13
0
        public async Task AuthenticateRequestAsync(HttpRequestMessage request)
        {
            AuthenticationResult authResult = null;

            var accounts = await _application.GetAccountsAsync();

            var firstAccount = accounts.FirstOrDefault();

            try
            {
                authResult = await _application.AcquireTokenSilent(_scopes, accounts.FirstOrDefault())
                             .ExecuteAsync();
            }
            catch (MsalUiRequiredException)
            {
                try
                {
                    await Application.Current.Dispatcher.Invoke(async() =>
                    {
                        authResult = await _application.AcquireTokenInteractive(_scopes)
                                     .WithParentActivityOrWindow(new WindowInteropHelper(Application.Current.MainWindow).Handle)
                                     .ExecuteAsync();
                    });
                }
                catch { }
            }

            if (authResult != null)
            {
                request.Headers.Authorization = new AuthenticationHeaderValue("bearer", authResult.AccessToken);
            }
        }
Exemple #14
0
        private async Task AuthenticateAsync()
        {
            _appClient = PublicClientApplicationBuilder.Create(_clientId)
                         .WithAuthority(_authority)
                         .WithRedirectUri(_redirectUri)
                         .WithDebugLoggingCallback(Microsoft.Identity.Client.LogLevel.Verbose)
                         .Build();
            _appClient.UserTokenCache.SetBeforeAccessAsync(OnBeforeAccessTokenCacheAsync);
            _appClient.UserTokenCache.SetAfterAccessAsync(OnAfterAccessTokenCacheAsync);
            IAccount account = (await _appClient.GetAccountsAsync()).FirstOrDefault();

            try
            {
                _authenticationResult = await _appClient.AcquireTokenSilent(_scopes, account)
                                        .ExecuteAsync();
            }
            catch (MsalUiRequiredException ex)
            {
                try
                {
                    _authenticationResult = await _appClient.AcquireTokenInteractive(_scopes)
                                            .WithAccount(account)
                                            .ExecuteAsync();
                }
                catch (Exception msalUiError)
                {
                    ShowError(msalUiError.Message, "MSAL Error");
                }
            }
            catch (Exception ex)
            {
                ShowError(ex.Message, "Error");
            }
        }
Exemple #15
0
        /// <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));
            }));
        }
Exemple #16
0
        /// <summary>
        /// Signs in the user and obtains an access token for Microsoft Graph
        /// </summary>
        /// <param name="scopes"></param>
        /// <returns> Access Token</returns>
        private static async Task <string> SignInUserAndGetTokenUsingMSAL(string[] scopes)
        {
            // Initialize the MSAL library by building a public client application
            PublicClientApp = PublicClientApplicationBuilder.Create(ClientId)
                              .WithAuthority(Authority)
                              .WithUseCorporateNetwork(false)
                              .WithDefaultRedirectUri()
                              .WithLogging((level, message, containsPii) =>
            {
                Debug.WriteLine($"MSAL: {level} {message} ");
            }, LogLevel.Warning, enablePiiLogging: false, enableDefaultPlatformLogging: true)
                              .Build();

            // It's good practice to not do work on the UI thread, so use ConfigureAwait(false) whenever possible.
            IEnumerable <IAccount> accounts = await PublicClientApp.GetAccountsAsync().ConfigureAwait(false);

            IAccount firstAccount = accounts.FirstOrDefault();

            try
            {
                authResult = await PublicClientApp.AcquireTokenSilent(scopes, firstAccount)
                             .ExecuteAsync();
            }
            catch (MsalUiRequiredException ex)
            {
                // A MsalUiRequiredException happened on AcquireTokenSilentAsync. This indicates you need to call AcquireTokenAsync to acquire a token
                Debug.WriteLine($"MsalUiRequiredException: {ex.Message}");

                authResult = await PublicClientApp.AcquireTokenInteractive(scopes)
                             .ExecuteAsync()
                             .ConfigureAwait(false);
            }
            return(authResult.AccessToken);
        }
Exemple #17
0
        public async Task <string> GetAccessTokenAsync(string[] scopes)
        {
            var acquireTokenSuccess = await AcquireTokenSilentAsync(scopes);

            if (acquireTokenSuccess)
            {
                return(_authenticationResult.AccessToken);
            }
            else
            {
                try
                {
                    // Interactive authentication is required
                    var accounts = await _client.GetAccountsAsync();

                    _authenticationResult = await _client.AcquireTokenInteractive(scopes)
                                            .WithAccount(accounts.FirstOrDefault())
                                            .ExecuteAsync();

                    return(_authenticationResult.AccessToken);
                }
                catch (MsalException)
                {
                    // AcquireTokenSilent and AcquireTokenInteractive failed, the session will be closed.
                    _authenticationResult = null;
                    LoggedOut?.Invoke(this, EventArgs.Empty);
                    return(string.Empty);
                }
            }
        }
Exemple #18
0
        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);
            }
        }
        // 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);
        }
Exemple #20
0
        /// <summary>
        /// Ensure the user is logged in
        /// </summary>
        /// <returns>The access token</returns>
        public static async Task <string> EnsureSignInAsync()
        {
            IPublicClientApplication publicClientApp = PublicClientApplicationBuilder.Create(ClientId)
                                                       .WithB2CAuthority(SignUpSignInAuthority)
                                                       .WithRedirectUri(RedirectUri)
                                                       .WithLogging(PublicClientLog, LogLevel.Info, false)
                                                       .Build();

            TokenCache.Bind(publicClientApp.UserTokenCache);

            AuthenticationResult authResult = null;
            var scopes = new string[] { Scope };

            try
            {
                // Attempt to silently aquire the user token
                var accounts = await publicClientApp.GetAccountsAsync(SignUpSignInPolicyId);

                authResult = await publicClientApp.AcquireTokenSilent(scopes, accounts.FirstOrDefault())
                             .ExecuteAsync();
            }
            catch (MsalUiRequiredException)
            {
                // Ignore, user will need to sign in interactively.
                authResult = await publicClientApp.AcquireTokenInteractive(scopes)
                             .ExecuteAsync();
            }

            return(authResult.AccessToken);
        }
Exemple #21
0
        public async void OnStart(IFileStorageSetupActivity activity)
        {
            if (activity.ProcessName.Equals(FileStorageSetupDefs.ProcessNameFileUsageSetup))
            {
                activity.State.PutString(FileStorageSetupDefs.ExtraPath, activity.Ioc.Path);
            }
            string rootPathForUser = await TryLoginSilent(activity.Ioc.Path);

            if (rootPathForUser != null)
            {
                FinishActivityWithSuccess(activity, rootPathForUser);
            }

            try
            {
                logDebug("try interactive");
                AuthenticationResult res = await _publicClientApp.AcquireTokenInteractive(Scopes)
                                           .WithParentActivityOrWindow((Activity)activity)
                                           .ExecuteAsync();

                logDebug("ok interactive");
                BuildClient(res);
                FinishActivityWithSuccess(activity, BuildRootPathForUser(res));
            }
            catch (Exception e)
            {
                logDebug("authenticating not successful: " + e);
                Intent data = new Intent();
                data.PutExtra(FileStorageSetupDefs.ExtraErrorMessage, "authenticating not successful");
                ((Activity)activity).SetResult(Result.Canceled, data);
                ((Activity)activity).Finish();
            }
        }
Exemple #22
0
        /// <summary>
        /// Sign-in user using MSAL and obtain an access token for Azure DevOps
        /// </summary>
        /// <param name="scopes"></param>
        /// <returns>AuthenticationResult</returns>
        private static async Task <AuthenticationResult> SignInUserAndGetTokenUsingMSAL(string[] scopes)
        {
            // Initialize the MSAL library by building a public client application
            application = PublicClientApplicationBuilder.Create(clientId)
                          .WithAuthority(authority)
                          .WithDefaultRedirectUri()
                          .Build();

            AuthenticationResult result;

            try
            {
                var accounts = await application.GetAccountsAsync();

                result = await application.AcquireTokenSilent(scopes, accounts.FirstOrDefault())
                         .ExecuteAsync();
            }
            catch (MsalUiRequiredException ex)
            {
                // If the token has expired, prompt the user with a login prompt
                result = await application.AcquireTokenInteractive(scopes)
                         .WithClaims(ex.Claims)
                         .ExecuteAsync();
            }
            return(result);
        }
Exemple #23
0
        private static async Task <string> SignInUserAndGetTokenUsingMSAL(PublicClientApplicationOptions configuration, string[] scopes)
        {
            string authority = string.Concat(configuration.Instance, configuration.TenantId);

            // Initialize the MSAL library by building a public client application
            application = PublicClientApplicationBuilder.Create(configuration.ClientId)
                          .WithAuthority(authority)
                          .WithDefaultRedirectUri()
                          .Build();


            AuthenticationResult result;

            try
            {
                var accounts = await application.GetAccountsAsync();

                result = await application.AcquireTokenSilent(scopes, accounts.FirstOrDefault())
                         .ExecuteAsync();
            }
            catch (MsalUiRequiredException ex)
            {
                result = await application.AcquireTokenInteractive(scopes)
                         .WithClaims(ex.Claims)
                         .ExecuteAsync();
            }

            return(result.AccessToken);
        }
        /// <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;
            }
        }
        private static async Task <string> SignInUserAndGetTokenUsingMSAL(string[] scopes)
        {
            PublicClientApp = PublicClientApplicationBuilder.Create(ClientId)
                              .WithAuthority(Authority)
                              .WithUseCorporateNetwork(false)
                              .WithRedirectUri(DefaultRedirectUri.Value)
                              .WithLogging((level, message, containsPii) =>
            {
                Debug.WriteLine($"MSAL: {level} {message} ");
            }, LogLevel.Warning, enablePiiLogging: false, enableDefaultPlatformLogging: true)
                              .Build();

            var accounts = await PublicClientApp.GetAccountsAsync().ConfigureAwait(false);

            var firstAccount = accounts.FirstOrDefault();

            try
            {
                authResult = await PublicClientApp.AcquireTokenSilent(scopes, firstAccount)
                             .ExecuteAsync();
            }
            catch (MsalUiRequiredException ex)
            {
                // A MsalUiRequiredException happened on AcquireTokenSilentAsync. This indicates you need to call AcquireTokenAsync to acquire a token
                Debug.WriteLine($"MsalUiRequiredException: {ex.Message}");

                authResult = await PublicClientApp.AcquireTokenInteractive(scopes)
                             .ExecuteAsync()
                             .ConfigureAwait(false);
            }
            return(authResult.AccessToken);
        }
        private static async Task <string> AcquireAccessTokenAsync()
        {
            if (AadClientApplicationId == "#PLACEHOLDER#" || AadScopes.Length == 0 || AadRedirectUri == "#PLACEHOLDER#" || AadTenantName.StartsWith("#PLACEHOLDER#"))
            {
                throw new Exception($"Use the link {"https://docs.microsoft.com/azure/time-series-insights/time-series-insights-get-started"} to update the values of 'AadClientApplicationId', 'AadScopes', 'AadRedirectUri', and 'AadAuthenticationAuthority'.");
            }

            /**
             * MSAL.NET configuration. Review the product documentation for more information about MSAL.NET authentication options.
             *
             * https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/wiki/
             */

            IPublicClientApplication app = PublicClientApplicationBuilder
                                           .Create(AadClientApplicationId)
                                           .WithRedirectUri(AadRedirectUri)
                                           .WithAuthority(AadAuthenticationAuthority)
                                           .Build();

            AuthenticationResult result = await app
                                          .AcquireTokenInteractive(AadScopes)
                                          .ExecuteAsync();

            Console.WriteLine("MSAL Authentication Token Acquired: {0}", result.AccessToken);
            Console.WriteLine("");
            return(result.AccessToken);
        }
        private async void AccessTokenButton_ClickAsync(object sender, RoutedEventArgs e)
        {
            CreatePublicClient();
            AuthenticationResult result = null;

            try
            {
                IEnumerable <IAccount> users = await _pca.GetAccountsAsync().ConfigureAwait(false);

                IAccount user = users.FirstOrDefault();

                result = await _pca.AcquireTokenInteractive(s_scopes)
                         .ExecuteAsync(CancellationToken.None)
                         .ConfigureAwait(false);

                await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
                                          () =>
                {
                    AccessToken.Text = "\nAccessToken: \n" + result.AccessToken;
                });
            }
            catch (Exception ex)
            {
                await DisplayErrorAsync(ex).ConfigureAwait(false);

                return;
            }

            await DisplayResultAsync(result).ConfigureAwait(false);
        }
Exemple #28
0
        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;
            }
        }
Exemple #29
0
        private static async Task ConsumeSPOWithOAuthAccessToken(string targetSiteUrl)
        {
            var spoTenant = targetSiteUrl.Substring(0, targetSiteUrl.IndexOf('/', 8));

            PublicClientApp = PublicClientApplicationBuilder.Create(ClientId)
                              .WithDefaultRedirectUri()
                              .Build();

            var _scopes = new String[] { $"{spoTenant}/AllSites.Read" };

            var authResult = await PublicClientApp.AcquireTokenInteractive(_scopes)
                             .ExecuteAsync();

            Console.WriteLine("Here is the Access Token for Graph API:");
            Console.WriteLine(authResult.AccessToken);
            var handler = new JwtSecurityTokenHandler();
            var token   = handler.ReadJwtToken(authResult.AccessToken);

            var authManager = new AuthenticationManager();

            using (var context = authManager.GetAzureADAccessTokenAuthenticatedContext(targetSiteUrl, authResult.AccessToken))
            {
                var web = context.Web;
                context.Load(web, w => w.Title);
                context.ExecuteQueryRetry();

                Console.WriteLine($"The site title is: {web.Title}");
            }
        }
Exemple #30
0
        /// <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));
        }