/// <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>
        /// <param name="claimsPrincipal"></param>
        /// <returns></returns>
        private IConfidentialClientApplication BuildConfidentialClientApplication()
        {
            var    request            = CurrentHttpContext.Request;
            var    azureAdOptions     = _azureAdOptions;
            var    applicationOptions = _applicationOptions;
            string currentUri         = UriHelper.BuildAbsolute(
                request.Scheme,
                request.Host,
                request.PathBase,
                azureAdOptions.CallbackPath ?? string.Empty);

            string authority = $"{applicationOptions.Instance}{applicationOptions.TenantId}/";

            var app = ConfidentialClientApplicationBuilder
                      .CreateWithApplicationOptions(applicationOptions)
                      .WithRedirectUri(currentUri)
                      .WithAuthority(authority)
                      .Build();

            // Initialize token cache providers
            _tokenCacheProvider?.InitializeAsync(app.AppTokenCache);
            _tokenCacheProvider?.InitializeAsync(app.UserTokenCache);

            return(app);
        }
        /// <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>
        /// <param name="claimsPrincipal"></param>
        /// <returns></returns>
        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("/"))
            {
                _applicationOptions.Instance += "/";
            }

            string authority;
            IConfidentialClientApplication app;

            try
            {
                if (_microsoftIdentityOptions.IsB2C)
                {
                    authority = $"{ _applicationOptions.Instance}tfp/{_microsoftIdentityOptions.Domain}/{_microsoftIdentityOptions.DefaultUserFlow}";
                    app       = ConfidentialClientApplicationBuilder
                                .CreateWithApplicationOptions(_applicationOptions)
                                .WithRedirectUri(currentUri)
                                .WithB2CAuthority(authority)
                                .Build();
                }
                else
                {
                    authority = $"{ _applicationOptions.Instance}{_applicationOptions.TenantId}/";

                    app = ConfidentialClientApplicationBuilder
                          .CreateWithApplicationOptions(_applicationOptions)
                          .WithRedirectUri(currentUri)
                          .WithAuthority(authority)
                          .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, "Exception acquiring token for a confidential client. ");
                throw;
            }
        }
        /// <summary>
        /// Creates an MSAL Confidential client application
        /// </summary>
        /// <param name="claimsPrincipal"></param>
        /// <returns></returns>
        private IConfidentialClientApplication BuildConfidentialClientApplication()
        {
            var    request = CurrentHttpContext.Request;
            var    microsoftIdentityOptions = _microsoftIdentityOptions;
            var    applicationOptions       = _applicationOptions;
            string currentUri = UriHelper.BuildAbsolute(
                request.Scheme,
                request.Host,
                request.PathBase,
                microsoftIdentityOptions.CallbackPath.Value ?? string.Empty);

            if (!applicationOptions.Instance.EndsWith("/"))
            {
                applicationOptions.Instance += "/";
            }

            string authority;
            IConfidentialClientApplication app = null;

            if (microsoftIdentityOptions.IsB2C)
            {
                authority = $"{applicationOptions.Instance}tfp/{microsoftIdentityOptions.Domain}/{microsoftIdentityOptions.DefaultUserFlow}";
                app       = ConfidentialClientApplicationBuilder
                            .CreateWithApplicationOptions(applicationOptions)
                            .WithRedirectUri(currentUri)
                            .WithB2CAuthority(authority)
                            .Build();
            }
            else
            {
                authority = $"{applicationOptions.Instance}{applicationOptions.TenantId}/";
                app       = ConfidentialClientApplicationBuilder
                            .CreateWithApplicationOptions(applicationOptions)
                            .WithRedirectUri(currentUri)
                            .WithAuthority(authority)
                            .Build();
            }

            // Initialize token cache providers
            _tokenCacheProvider?.InitializeAsync(app.AppTokenCache);
            _tokenCacheProvider?.InitializeAsync(app.UserTokenCache);

            return(app);
        }
예제 #6
0
        private async Task <IConfidentialClientApplication> GetOrCreateApplication()
        {
            if (_confidentialClientApplication == null)
            {
                ConfidentialClientApplicationOptions options = new ConfidentialClientApplicationOptions()
                {
                    ClientId     = AppServicesAuthenticationInformation.ClientId,
                    ClientSecret = AppServicesAuthenticationInformation.ClientSecret,
                    Instance     = AppServicesAuthenticationInformation.Issuer,
                };
                _confidentialClientApplication = ConfidentialClientApplicationBuilder.CreateWithApplicationOptions(options)
                                                 .WithHttpClientFactory(_httpClientFactory)
                                                 .Build();
                await _tokenCacheProvider.InitializeAsync(_confidentialClientApplication.AppTokenCache).ConfigureAwait(false);

                await _tokenCacheProvider.InitializeAsync(_confidentialClientApplication.UserTokenCache).ConfigureAwait(false);
            }

            return(_confidentialClientApplication);
        }
예제 #7
0
        public static async Task <IConfidentialClientApplication> BuildConfidentialClientApplication()
        {
            IConfidentialClientApplication clientapp = ConfidentialClientApplicationBuilder.Create(AuthenticationConfig.ClientId)
                                                       .WithClientSecret(AuthenticationConfig.ClientSecret)
                                                       .WithRedirectUri(AuthenticationConfig.RedirectUri)
                                                       .WithAuthority(new Uri(AuthenticationConfig.Authority))
                                                       .Build();

            // After the ConfidentialClientApplication is created, we overwrite its default UserTokenCache serialization with our implementation
            IMsalTokenCacheProvider memoryTokenCacheProvider = CreateTokenCacheSerializer();
            await memoryTokenCacheProvider.InitializeAsync(clientapp.UserTokenCache);

            return(clientapp);
        }
예제 #8
0
        static async Task Main(string[] args)
        {
            string clientId     = "812287fd-3ea3-49c6-b4ab-e8d41dea1f17";
            string clientSecret = "[Enter here the secret register with your application]";
            string tenant       = "msidentitysamplestesting.onmicrosoft.com";

            string[] scopes = new[] { "api://2d96f90e-a1a7-4ef5-b15c-87758986eb1a/.default" };

            CacheImplementationDemo cacheImplementation = CacheImplementationDemo.InMemory;

            // Create the token cache (4 possible implementations)
            IMsalTokenCacheProvider msalTokenCacheProvider = CreateTokenCache(cacheImplementation);

            // Create the confidential client application
            IConfidentialClientApplication app;

            app = ConfidentialClientApplicationBuilder.Create(clientId)
                  .WithClientSecret(clientSecret)
                  .WithTenantId(tenant)
                  .Build();

            await msalTokenCacheProvider.InitializeAsync(app.UserTokenCache);

            await msalTokenCacheProvider.InitializeAsync(app.AppTokenCache);

            // Acquire a token (twice)
            var result = await app.AcquireTokenForClient(scopes)
                         .ExecuteAsync();

            Console.WriteLine(result.AuthenticationResultMetadata.TokenSource);

            result = await app.AcquireTokenForClient(scopes)
                     .ExecuteAsync();

            Console.WriteLine(result.AuthenticationResultMetadata.TokenSource);
        }
예제 #9
0
        public static async Task RemoveAccount()
        {
            IConfidentialClientApplication clientapp = ConfidentialClientApplicationBuilder.Create(AuthenticationConfig.ClientId)
                                                       .WithClientSecret(AuthenticationConfig.ClientSecret)
                                                       .WithRedirectUri(AuthenticationConfig.RedirectUri)
                                                       .WithAuthority(new Uri(AuthenticationConfig.Authority))
                                                       .Build();

            // We only clear the user's tokens.
            IMsalTokenCacheProvider memoryTokenCacheProvider = CreateTokenCacheSerializer();
            await memoryTokenCacheProvider.InitializeAsync(clientapp.UserTokenCache);

            var userAccount = await clientapp.GetAccountAsync(ClaimsPrincipal.Current.GetAccountId());

            if (userAccount != null)
            {
                await clientapp.RemoveAsync(userAccount);
            }
        }
        /// <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;
            }
        }
예제 #11
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;
            }
        }