/// <summary>
        /// Creates an MSAL Confidential client application.
        /// </summary>
        private async Task <IConfidentialClientApplication> BuildConfidentialClientApplicationAsync()
        {
            if (!_applicationOptions.Instance.EndsWith("/", StringComparison.InvariantCulture))
            {
                _applicationOptions.Instance += "/";
            }

            string authority;
            IConfidentialClientApplication app;

            MicrosoftIdentityOptionsValidation microsoftIdentityOptionsValidation = new MicrosoftIdentityOptionsValidation();

            if (microsoftIdentityOptionsValidation.ValidateClientSecret(_applicationOptions).Failed)
            {
                string msg = string.Format(CultureInfo.InvariantCulture, "Client secret cannot be null or whitespace, " +
                                           "and must be included in the configuration of the web app when calling a web API. " +
                                           "For instance, in the appsettings.json file. ");

                _logger.LogInformation(msg);
                throw new MsalClientException(
                          "missing_client_credentials",
                          msg);
            }

            try
            {
                var builder = ConfidentialClientApplicationBuilder
                              .CreateWithApplicationOptions(_applicationOptions)
                              .WithRedirectUri(CreateRedirectUri())
                              .WithHttpClientFactory(_httpClientFactory);

                if (_microsoftIdentityOptions.IsB2C)
                {
                    authority = $"{ _applicationOptions.Instance}tfp/{_microsoftIdentityOptions.Domain}/{_microsoftIdentityOptions.DefaultUserFlow}";
                    builder.WithB2CAuthority(authority);
                    app = builder.Build();
                }
                else
                {
                    authority = $"{ _applicationOptions.Instance}{_applicationOptions.TenantId}/";
                    builder.WithAuthority(authority);
                    app = builder.Build();
                }

                // Initialize token cache providers
                await _tokenCacheProvider.InitializeAsync(app.AppTokenCache).ConfigureAwait(false);

                await _tokenCacheProvider.InitializeAsync(app.UserTokenCache).ConfigureAwait(false);

                return(app);
            }
            catch (Exception ex)
            {
                _logger.LogInformation(
                    ex,
                    string.Format(CultureInfo.InvariantCulture,
                                  "Exception acquiring token for a confidential client. "));
                throw;
            }
        }
        /// <summary>
        /// Creates an MSAL Confidential client application.
        /// </summary>
        private async Task <IConfidentialClientApplication> BuildConfidentialClientApplicationAsync()
        {
            if (!_applicationOptions.Instance.EndsWith("/", StringComparison.InvariantCulture))
            {
                _applicationOptions.Instance += "/";
            }

            string authority;
            IConfidentialClientApplication app;

            MicrosoftIdentityOptionsValidation microsoftIdentityOptionsValidation = new MicrosoftIdentityOptionsValidation();

            microsoftIdentityOptionsValidation.ValidateEitherClientCertificateOrClientSecret(
                _applicationOptions.ClientSecret,
                _microsoftIdentityOptions.ClientCertificates);

            try
            {
                var builder = ConfidentialClientApplicationBuilder
                              .CreateWithApplicationOptions(_applicationOptions)
                              .WithRedirectUri(CreateRedirectUri())
                              .WithHttpClientFactory(_httpClientFactory);

                if (_microsoftIdentityOptions.IsB2C)
                {
                    authority = $"{_applicationOptions.Instance}tfp/{_microsoftIdentityOptions.Domain}/{_microsoftIdentityOptions.DefaultUserFlow}";
                    builder.WithB2CAuthority(authority);
                }
                else
                {
                    authority = $"{_applicationOptions.Instance}{_applicationOptions.TenantId}/";
                    builder.WithAuthority(authority);
                }

                if (_microsoftIdentityOptions.ClientCertificates != null)
                {
                    X509Certificate2 certificate = DefaultCertificateLoader.LoadFirstCertificate(_microsoftIdentityOptions.ClientCertificates);
                    builder.WithCertificate(certificate);
                }

                app = builder.Build();
                // Initialize token cache providers
                await _tokenCacheProvider.InitializeAsync(app.AppTokenCache).ConfigureAwait(false);

                await _tokenCacheProvider.InitializeAsync(app.UserTokenCache).ConfigureAwait(false);

                return(app);
            }
            catch (Exception ex)
            {
                _logger.LogInformation(
                    ex,
                    string.Format(
                        CultureInfo.InvariantCulture,
                        "Exception acquiring token for a confidential client. "));
                throw;
            }
        }
        /// <summary>
        /// Creates an MSAL confidential client application.
        /// </summary>
        private async Task <IConfidentialClientApplication> BuildConfidentialClientApplicationAsync()
        {
            var    request    = CurrentHttpContext?.Request;
            string?currentUri = null;

            if (!string.IsNullOrEmpty(_applicationOptions.RedirectUri))
            {
                currentUri = _applicationOptions.RedirectUri;
            }

            if (request != null && string.IsNullOrEmpty(currentUri))
            {
                currentUri = UriHelper.BuildAbsolute(
                    request.Scheme,
                    request.Host,
                    request.PathBase,
                    _microsoftIdentityOptions.CallbackPath.Value ?? string.Empty);
            }

            PrepareAuthorityInstanceForMsal();

            MicrosoftIdentityOptionsValidation.ValidateEitherClientCertificateOrClientSecret(
                _applicationOptions.ClientSecret,
                _microsoftIdentityOptions.ClientCertificates);

            try
            {
                var builder = ConfidentialClientApplicationBuilder
                              .CreateWithApplicationOptions(_applicationOptions)
                              .WithHttpClientFactory(_httpClientFactory)
                              .WithLogging(
                    Log,
                    ConvertMicrosoftExtensionsLogLevelToMsal(_logger),
                    enablePiiLogging: _applicationOptions.EnablePiiLogging);

                // The redirect URI is not needed for OBO
                if (!string.IsNullOrEmpty(currentUri))
                {
                    builder.WithRedirectUri(currentUri);
                }

                string authority;

                if (_microsoftIdentityOptions.IsB2C)
                {
                    authority = $"{_applicationOptions.Instance}{ClaimConstants.Tfp}/{_microsoftIdentityOptions.Domain}/{_microsoftIdentityOptions.DefaultUserFlow}";
                    builder.WithB2CAuthority(authority);
                }
                else
                {
                    authority = $"{_applicationOptions.Instance}{_applicationOptions.TenantId}/";
                    builder.WithAuthority(authority);
                }

                if (_microsoftIdentityOptions.ClientCertificates != null)
                {
                    X509Certificate2?certificate = DefaultCertificateLoader.LoadFirstCertificate(_microsoftIdentityOptions.ClientCertificates);
                    builder.WithCertificate(certificate);
                }

                IConfidentialClientApplication app = builder.Build();
                _application = app;
                // Initialize token cache providers
                await _tokenCacheProvider.InitializeAsync(app.AppTokenCache).ConfigureAwait(false);

                await _tokenCacheProvider.InitializeAsync(app.UserTokenCache).ConfigureAwait(false);

                return(app);
            }
            catch (Exception ex)
            {
                _logger.LogInformation(
                    ex,
                    IDWebErrorMessage.ExceptionAcquiringTokenForConfidentialClient);
                throw;
            }
        }
Exemple #4
0
        /// <summary>
        /// Creates an MSAL Confidential client application.
        /// </summary>
        private async Task <IConfidentialClientApplication> BuildConfidentialClientApplicationAsync()
        {
            var    request    = CurrentHttpContext.Request;
            string currentUri = UriHelper.BuildAbsolute(
                request.Scheme,
                request.Host,
                request.PathBase,
                _microsoftIdentityOptions.CallbackPath.Value ?? string.Empty);

            if (!_applicationOptions.Instance.EndsWith("/", StringComparison.InvariantCulture))
            {
                _applicationOptions.Instance += "/";
            }

            MicrosoftIdentityOptionsValidation.ValidateEitherClientCertificateOrClientSecret(
                _applicationOptions.ClientSecret,
                _microsoftIdentityOptions.ClientCertificates);

            try
            {
                var builder = ConfidentialClientApplicationBuilder
                              .CreateWithApplicationOptions(_applicationOptions)
                              .WithRedirectUri(currentUri)
                              .WithHttpClientFactory(_httpClientFactory);

                string authority;

                if (_microsoftIdentityOptions.IsB2C)
                {
                    authority = $"{_applicationOptions.Instance}tfp/{_microsoftIdentityOptions.Domain}/{_microsoftIdentityOptions.DefaultUserFlow}";
                    builder.WithB2CAuthority(authority);
                }
                else
                {
                    authority = $"{_applicationOptions.Instance}{_applicationOptions.TenantId}/";
                    builder.WithAuthority(authority);
                }

                if (_microsoftIdentityOptions.ClientCertificates != null)
                {
                    X509Certificate2?certificate = DefaultCertificateLoader.LoadFirstCertificate(_microsoftIdentityOptions.ClientCertificates);
                    builder.WithCertificate(certificate);
                }

                IConfidentialClientApplication app = builder.Build();
                // Initialize token cache providers
                await _tokenCacheProvider.InitializeAsync(app.AppTokenCache).ConfigureAwait(false);

                await _tokenCacheProvider.InitializeAsync(app.UserTokenCache).ConfigureAwait(false);

                return(app);
            }
            catch (Exception ex)
            {
                _logger.LogInformation(
                    ex,
                    string.Format(
                        CultureInfo.InvariantCulture,
                        IDWebErrorMessage.ExceptionAcquiringTokenForConfidentialClient));
                throw;
            }
        }
Exemple #5
0
        /// <summary>
        /// Creates an MSAL confidential client application.
        /// </summary>
        private IConfidentialClientApplication BuildConfidentialClientApplication()
        {
            var    httpContext = CurrentHttpContext;
            var    request     = httpContext?.Request;
            string?currentUri  = null;

            if (!string.IsNullOrEmpty(_applicationOptions.RedirectUri))
            {
                currentUri = _applicationOptions.RedirectUri;
            }

            if (request != null && string.IsNullOrEmpty(currentUri))
            {
                currentUri = BuildCurrentUriFromRequest(httpContext !, request);
            }

            PrepareAuthorityInstanceForMsal();

            MicrosoftIdentityOptionsValidation.ValidateEitherClientCertificateOrClientSecret(
                _applicationOptions.ClientSecret,
                _microsoftIdentityOptions.ClientCertificates);

            try
            {
                var builder = ConfidentialClientApplicationBuilder
                              .CreateWithApplicationOptions(_applicationOptions)
                              .WithHttpClientFactory(_httpClientFactory)
                              .WithLogging(
                    Log,
                    ConvertMicrosoftExtensionsLogLevelToMsal(_logger),
                    enablePiiLogging: _applicationOptions.EnablePiiLogging)
                              .WithExperimentalFeatures();

                // The redirect URI is not needed for OBO
                if (!string.IsNullOrEmpty(currentUri))
                {
                    builder.WithRedirectUri(currentUri);
                }

                string authority;

                if (_microsoftIdentityOptions.IsB2C)
                {
                    authority = $"{_applicationOptions.Instance}{ClaimConstants.Tfp}/{_microsoftIdentityOptions.Domain}/{_microsoftIdentityOptions.DefaultUserFlow}";
                    builder.WithB2CAuthority(authority);
                }
                else
                {
                    authority = $"{_applicationOptions.Instance}{_applicationOptions.TenantId}/";
                    builder.WithAuthority(authority);
                }

                if (_microsoftIdentityOptions.ClientCertificates != null)
                {
                    X509Certificate2?certificate = DefaultCertificateLoader.LoadFirstCertificate(_microsoftIdentityOptions.ClientCertificates);
                    builder.WithCertificate(certificate);
                }

                IConfidentialClientApplication app = builder.Build();
                _application = app;
                // Initialize token cache providers
                _tokenCacheProvider.Initialize(app.AppTokenCache);
                _tokenCacheProvider.Initialize(app.UserTokenCache);
                return(app);
            }
            catch (Exception ex)
            {
                Logger.TokenAcquisitionError(
                    _logger,
                    IDWebErrorMessage.ExceptionAcquiringTokenForConfidentialClient,
                    ex);
                throw;
            }
        }