private ClientContext BuildClientContext(IClientApplicationBase application, string siteUrl, string[] scopes, ClientContextType contextType)
        {
            var clientContext = new ClientContext(siteUrl)
            {
                DisableReturnValueCache = true
            };

            clientContext.ExecutingWebRequest += (sender, args) =>
            {
                AuthenticationResult ar = null;

                var accounts = application.GetAccountsAsync().GetAwaiter().GetResult();
                if (accounts.Count() > 0)
                {
                    ar = application.AcquireTokenSilent(scopes, accounts.First()).ExecuteAsync().GetAwaiter().GetResult();
                }
                else
                {
                    switch (contextType)
                    {
                    case ClientContextType.AzureADCertificate:
                    {
                        ar = ((IConfidentialClientApplication)application).AcquireTokenForClient(scopes).ExecuteAsync().GetAwaiter().GetResult();
                        break;
                    }

                    case ClientContextType.AzureADCredentials:
                    {
                        ar = ((IPublicClientApplication)application).AcquireTokenByUsernamePassword(scopes, username, password).ExecuteAsync().GetAwaiter().GetResult();
                        break;
                    }

                    case ClientContextType.AzureADInteractive:
                    {
                        ar = ((IPublicClientApplication)application).AcquireTokenInteractive(scopes).ExecuteAsync().GetAwaiter().GetResult();
                        break;
                    }
                    }
                }
                if (ar != null && ar.AccessToken != null)
                {
                    args.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + ar.AccessToken;
                }
            };

            ClientContextSettings clientContextSettings = new ClientContextSettings()
            {
                Type    = contextType,
                SiteUrl = siteUrl,
                AuthenticationManager = this,
            };

            clientContext.AddContextSettings(clientContextSettings);

            return(clientContext);
        }
Example #2
0
        /// <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);
            }
        }
        /// <summary>
        /// Apply this authenticator to the given authentication parameters.
        /// </summary>
        /// <param name="parameters">The complex object containing authentication specific information.</param>
        /// <param name="promptAction">The action used to prompt for interaction.</param>
        /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
        /// <returns>
        /// An instance of <see cref="AuthenticationResult" /> that represents the access token generated as result of a successful authenication.
        /// </returns>
        public override async Task <AuthenticationResult> AuthenticateAsync(AuthenticationParameters parameters, Action <string> promptAction = null, CancellationToken cancellationToken = default)
        {
            IClientApplicationBase app = GetClient(parameters.Account, parameters.Environment);
            IAccount account           = await app.GetAccountAsync(parameters.Account.Identifier).ConfigureAwait(false);

            if (account != null)
            {
                return(await app.AcquireTokenSilent(parameters.Scopes, account).ExecuteAsync(cancellationToken).ConfigureAwait(false));
            }

            return(await app.AsRefreshTokenClient().AcquireTokenByRefreshToken(
                       parameters.Scopes,
                       parameters.Account.GetProperty(PartnerAccountPropertyType.RefreshToken)).ExecuteAsync(cancellationToken).ConfigureAwait(false));
        }
Example #4
0
        /// <summary>
        /// Apply this authenticator to the given authentication parameters.
        /// </summary>
        /// <param name="parameters">The complex object containing authentication specific information.</param>
        /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
        /// <returns>
        /// An instance of <see cref="AuthenticationResult" /> that represents the access token generated as result of a successful authenication.
        /// </returns>
        public override async Task <AuthenticationResult> AuthenticateAsync(AuthenticationParameters parameters, CancellationToken cancellationToken = default)
        {
            IClientApplicationBase app = GetClient(parameters.Account, parameters.Environment);

            ServiceClientTracing.Information("[RefreshTokenAuthenticator] Calling GetAccountsAysnc");
            IAccount account = await app.GetAccountAsync(parameters.Account.Identifier).ConfigureAwait(false);

            if (account != null)
            {
                ServiceClientTracing.Information($"[RefreshTokenAuthenticator] Calling AcquireTokenSilent - Scopes: '{string.Join(", ", parameters.Scopes)}'");
                return(await app.AcquireTokenSilent(parameters.Scopes, account).ExecuteAsync(cancellationToken).ConfigureAwait(false));
            }

            ServiceClientTracing.Information($"[RefreshTokenAuthenticator] Calling AcquireTokenByRefreshToken - Scopes: '{string.Join(", ", parameters.Scopes)}'");
            return(await app.AsRefreshTokenClient().AcquireTokenByRefreshToken(
                       parameters.Scopes,
                       parameters.Account.GetProperty(PartnerAccountPropertyType.RefreshToken)).ExecuteAsync(cancellationToken).ConfigureAwait(false));
        }
Example #5
0
 public Task <AuthenticationResult> AcquireTokenSilentAsync(IAccount account) =>
 _Identity
 .AcquireTokenSilent(Scopes, account)
 .ExecuteAsync();