Exemple #1
0
        protected async Task <(string, string)> GetAccessToken()
        {
            IConfidentialClientApplication app = ConfidentialClientApplicationBuilder.Create(this.AppSettings.ClientId)
                                                 .WithClientSecret(this.AppSettings.ClientSecret)
                                                 .WithAuthority(new Uri(_authority))
                                                 .Build();

            string[]             scopes = new string[] { this.AppSettings.scope };
            AuthenticationResult result = null;

            try {
                result = await app.AcquireTokenForClient(scopes).ExecuteAsync();
            } catch (Exception ex) {
                return(String.Empty, ex.Message);
            }
            _log.LogTrace(result.AccessToken);
            return(result.AccessToken, String.Empty);
        }
Exemple #2
0
        public GraphAuthProvider(IConfiguration configuration)
        {
            var azureOptions = new AzureAdOptions();

            configuration.Bind("AzureAd", azureOptions);

            // More info about MSAL Client Applications: https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/wiki/Client-Applications
            _app = ConfidentialClientApplicationBuilder
                   .Create(azureOptions.ClientId)
                   .WithClientSecret(azureOptions.ClientSecret)
                   .WithAuthority(AzureCloudInstance.AzurePublic, AadAuthorityAudience.AzureAdAndPersonalMicrosoftAccount)
                   .WithRedirectUri(azureOptions.BaseUrl + azureOptions.CallbackPath)
                   .Build();

            Authority = _app.Authority;

            _scopes = azureOptions.GraphScopes.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
        }
        public ClientCredentialsAuthenticationManager(
            AzureEnvironment azureEnvironment,
            Guid tenantId,
            Guid applicationClientId,
            string clientSecret
            )
        {
            _azureEnvironment = azureEnvironment;
            var azureCloudInstance = azureEnvironment.ToAzureCloudInstance();

            _tenantId = tenantId;

            _confidentialClientApplication = ConfidentialClientApplicationBuilder
                                             .Create(applicationClientId.ToString())
                                             .WithAuthority(azureCloudInstance, tenantId)
                                             .WithClientSecret(clientSecret)
                                             .Build();
        }
Exemple #4
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ADGroupsDataRepository"/> class.
        /// </summary>
        /// <param name="configuration">Represents the application configuration.</param>
        /// <param name="isFromAzureFunction">Flag to show if created from Azure Function.</param>
        public ADGroupsDataRepository(IConfiguration configuration, bool isFromAzureFunction = false)
            : base(
                configuration,
                PartitionKeyNames.TeamDataTable.TableName,
                PartitionKeyNames.TeamDataTable.TeamDataPartition,
                isFromAzureFunction)
        {
            this.configuration = configuration;
            var microsoftAppId       = this.configuration["MicrosoftAppId"];
            var microsoftAppPassword = this.configuration["MicrosoftAppPassword"];
            var aadinstance          = this.configuration["AADInstance"];
            var tenantid             = this.configuration["TenantId"];

            this.app = ConfidentialClientApplicationBuilder.Create(microsoftAppId)
                       .WithClientSecret(microsoftAppPassword)
                       .WithAuthority(new Uri(string.Format(CultureInfo.InvariantCulture, aadinstance, tenantid)))
                       .Build();
        }
        public async Task <string> LoginAsync()
        {
            //https://login.microsoftonline.com/{tenant}
            var authority = $"https://login.microsoftonline.com/{tenantId}";
            IConfidentialClientApplication app = ConfidentialClientApplicationBuilder.Create(clientId)
                                                 .WithClientSecret(clientSecret)
                                                 .WithAuthority(new Uri(authority))
                                                 .Build();

            var scopes = new List <string>()
            {
                "https://api.timeseries.azure.com/.default"
            };
            var result = await app.AcquireTokenForClient(scopes)
                         .ExecuteAsync();

            return(result.AccessToken);
        }
Exemple #6
0
        public GraphApiConnector(IConfigurationSection options)
        {
            _options = options;

            // Build a client application.
            IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
                                                                           .Create(_options["ClientId"])
                                                                           .WithTenantId(_options["TenantId"])
                                                                           .WithClientSecret(_options["ClientSecret"])
                                                                           .Build();
            // Create an authentication provider by passing in a client application and graph scopes.
            ClientCredentialProvider authProvider = new ClientCredentialProvider(confidentialClientApplication);

            // Create a new instance of GraphServiceClient with the authentication provider.
            graphClient = new GraphServiceClient(authProvider);

            UpdateUsers().Wait();
        }
Exemple #7
0
        public static async Task Initialize(string appId, string tenantID, string clientSecret, string principal)
        {
            IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
                                                                           .Create(appId)
                                                                           .WithTenantId(tenantID)
                                                                           .WithClientSecret(clientSecret)
                                                                           .Build();

            ClientCredentialProvider authenticationProvider = new ClientCredentialProvider(confidentialClientApplication);

            _graphClient = new GraphServiceClient(authenticationProvider);

            var user = await GetMeAsync(principal);

            _userId = user.Id;

            Console.WriteLine(">\tInitialized Email Listener on Email : <" + principal + ">");
        }
Exemple #8
0
        /// <summary>
        /// Removes the account associated with context.HttpContext.User from the MSAL.NET cache
        /// </summary>
        /// <param name="context">RedirectContext passed-in to a <see cref="OnRedirectToIdentityProviderForSignOut"/>
        /// Openidconnect event</param>
        /// <returns></returns>
        public async Task RemoveAccount(RedirectContext context)
        {
            ClaimsPrincipal user = context.HttpContext.User;
            IConfidentialClientApplication app = BuildConfidentialClientApplication(context.HttpContext, user);
            IAccount account = await app.GetAccountAsync(context.HttpContext.User.GetMsalAccountId());

            // Workaround for the guest account
            if (account == null)
            {
                var accounts = await app.GetAccountsAsync();

                account = accounts.FirstOrDefault(a => a.Username == user.GetLoginHint());
            }

            this.UserTokenCacheProvider?.Clear();

            await app.RemoveAsync(account);
        }
        public async Task AcquireTokenToRegionalEndpointAsync()
        {
            // Arrange
            var factory  = new HttpSnifferClientFactory();
            var settings = ConfidentialAppSettings.GetSettings(Cloud.Public);

            _confidentialClientApplication = BuildCCA(settings, factory);

            Environment.SetEnvironmentVariable(TestConstants.RegionName, TestConstants.Region);
            AuthenticationResult result = await GetAuthenticationResultAsync(settings.AppScopes).ConfigureAwait(false); // regional endpoint

            AssertTokenSourceIsIdp(result);
            AssertValidHost(true, factory);
            AssertTelemetry(factory, $"{TelemetryConstants.HttpTelemetrySchemaVersion}|1004,{CacheRefreshReason.NoCachedAccessToken:D},centralus,3,4|0,1");
            Assert.AreEqual(
                $"https://centralus.r.login.microsoftonline.com/{settings.TenantId}/oauth2/v2.0/token",
                result.AuthenticationResultMetadata.TokenEndpoint);
        }
Exemple #10
0
        static TokenProvider ClientCredentialsScenario(string ClientId, string clientSecret, string TenantId)
        {
            TokenProvider aadTokenProvider = TokenProvider.CreateAzureActiveDirectoryTokenProvider
                                                 (async(audience, authority, state) =>
            {
                IConfidentialClientApplication app = ConfidentialClientApplicationBuilder.Create(ClientId)
                                                     .WithAuthority(authority)
                                                     .WithClientSecret(clientSecret)
                                                     .Build();

                var serviceBusAudience = new Uri("https://servicebus.azure.net");

                AuthenticationResult authResult = await app.AcquireTokenForClient(new string[] { $"{serviceBusAudience}/.default" }).ExecuteAsync();
                return(authResult.AccessToken);
            }, $"https://login.windows.net/{TenantId}");

            return(aadTokenProvider);
        }
Exemple #11
0
        private static async Task RunAsync()
        {
            IConfidentialClientApplication clientApp = BuildClientUsingClientAssertion();

            // Request Access Token
            string[] scopes = new string[] {
                $"{FunctionAppAPIBaseUrl}/.default",
            };
            var result = await clientApp.AcquireTokenForClient(scopes)
                         .ExecuteAsync();

            Console.WriteLine("Access token: " + result.AccessToken);

            // Call Secured API using the Access Token
            var response = await CallEndpoint1(result);

            Console.WriteLine("Obtained response from secured endpoint: " + JsonConvert.SerializeObject(response));
        }
        private async Task OnAuthorizationCodeReceivedAsync(AuthorizationCodeReceivedNotification context)
        {
            // Upon successful sign-in, get the access token and cache it by using MSAL.

            IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
                                                                           .Create(System.Configuration.ConfigurationManager.AppSettings["ClientId"])
                                                                           .WithClientSecret(System.Configuration.ConfigurationManager.AppSettings["ClientSecret"])
                                                                           .WithTenantId(System.Configuration.ConfigurationManager.AppSettings["Tenant"])
                                                                           .WithRedirectUri(System.Configuration.ConfigurationManager.AppSettings["redirectUri"])
                                                                           .WithAuthority(System.Configuration.ConfigurationManager.AppSettings["Authority"])
                                                                           .Build();

            var result = await confidentialClientApplication.AcquireTokenByAuthorizationCode(new[] { "User.Read.All" }, context.Code).ExecuteAsync();



            context.Response.Cookies.Append("b", result.AccessToken);
        }
Exemple #13
0
        public static GraphServiceClient CreateGraphClient()
        {
            // Read application settings from appsettings.json (tenant ID, app ID, client secret, etc.)
            // AppSettings config = AppSettingsFile.ReadFromJsonFile();

            // Initialize the client credential auth provider
            IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
                                                                           .Create(Settings.Default.ManagementAppID)
                                                                           .WithTenantId(Settings.Default.TenantURL)
                                                                           .WithClientSecret(Settings.Default.ManagementAppClientSecret)
                                                                           .Build();
            ClientCredentialProvider authProvider = new ClientCredentialProvider(confidentialClientApplication);

            // Set up the Microsoft Graph service client with client credentials
            GraphServiceClient graphClient = new GraphServiceClient(authProvider);

            return(graphClient);
        }
Exemple #14
0
        /*
         * Callback function when an authorization code is received
         */
        private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification notification)
        {
            try
            {
                IConfidentialClientApplication confidentialClient = MsalAppBuilder.BuildConfidentialClientApplication(new ClaimsPrincipal(notification.AuthenticationTicket.Identity));

                // Upon successful sign in, get & cache a token using MSAL
                AuthenticationResult result = await confidentialClient.AcquireTokenByAuthorizationCode(B2C_Globals.Scopes, notification.Code).ExecuteAsync();
            }
            catch (Exception ex)
            {
                throw new HttpResponseException(new HttpResponseMessage
                {
                    StatusCode   = HttpStatusCode.BadRequest,
                    ReasonPhrase = $"Unable to get authorization code {ex.Message}."
                });
            }
        }
Exemple #15
0
        static async Task ClientCredentialsScenarioAsync()
        {
            TokenProvider tp = TokenProvider.CreateAzureActiveDirectoryTokenProvider(
                async(audience, authority, state) =>
            {
                IConfidentialClientApplication app = ConfidentialClientApplicationBuilder.Create(ClientId)
                                                     .WithAuthority(authority)
                                                     .WithClientSecret(ConfigurationManager.AppSettings["clientSecret"])
                                                     .Build();

                var authResult = await app.AcquireTokenForClient(new string[] { $"{audience}/.default" }).ExecuteAsync();
                return(authResult.AccessToken);
            });

            var ehClient = EventHubClient.CreateWithTokenProvider(new Uri($"sb://{EventHubNamespace}/"), EventHubName, tp);

            await SendReceiveAsync(ehClient);
        }
        public static async Task Main(string[] args)
        {
            // Create token provider so that we can use it at both management and runtime clients.
            TokenProvider tokenProvider = TokenProvider.CreateAzureActiveDirectoryTokenProvider(
                async(audience, authority, state) =>
            {
                IConfidentialClientApplication app = ConfidentialClientApplicationBuilder.Create(ClientId)
                                                     .WithAuthority(authority)
                                                     .WithClientSecret(ClientSecret)
                                                     .Build();

                var authResult = await app.AcquireTokenForClient(new string[] { $"{audience}/.default" }).ExecuteAsync();
                return(authResult.AccessToken);
            },
                ServiceAudience.EventHubsAudience,
                $"https://login.microsoftonline.com/{TenantId}");

            var eventHubName = "testeh-" + Guid.NewGuid().ToString();

            // Create NamespaceManger and EventHubClient with Azure Active Directory token provider.
            var ehUri            = new Uri($"sb://{EventHubNamespace}/");
            var namespaceManager = new NamespaceManager(ehUri, tokenProvider);
            var messagingFactory = MessagingFactory.Create(ehUri,
                                                           new MessagingFactorySettings()
            {
                TokenProvider = tokenProvider,
                TransportType = TransportType.Amqp
            });
            var ehClient = messagingFactory.CreateEventHubClient(eventHubName);

            // Create a new event hub.
            Console.WriteLine($"Creating event hub {eventHubName}");
            await namespaceManager.CreateEventHubAsync(eventHubName);

            // Send and receive a message.
            await SendReceiveAsync(ehClient);

            // Delete event hub.
            Console.WriteLine($"Deleting event hub {eventHubName}");
            await namespaceManager.DeleteEventHubAsync(eventHubName);

            Console.WriteLine("Press enter to exit");
            Console.ReadLine();
        }
        /// <summary>
        /// Creates a confidential client used for generating tokens.
        /// </summary>
        /// <param name="cloudInstance">The cloud instance used for authentication.</param>
        /// <param name="clientId">Identifier of the client requesting the token.</param>
        /// <param name="certificate">Certificate used by the client requesting the token.</param>
        /// <param name="clientSecret">Secret of the client requesting the token.</param>
        /// <param name="redirectUri">The redirect URI for the client.</param>
        /// <param name="tenantId">Identifier of the tenant requesting the token.</param>
        /// <returns>An aptly configured confidential client.</returns>
        private static IConfidentialClientApplication CreateConfidentialClient(
            AzureCloudInstance cloudInstance,
            string clientId              = null,
            string clientSecret          = null,
            X509Certificate2 certificate = null,
            string redirectUri           = null,
            string tenantId              = null)
        {
            ConfidentialClientApplicationBuilder builder = ConfidentialClientApplicationBuilder.Create(clientId);

            builder = builder.WithAuthority(cloudInstance, tenantId);

            if (!string.IsNullOrEmpty(clientSecret))
            {
                builder = builder.WithClientSecret(clientSecret);
            }

            if (certificate != null)
            {
                builder = builder.WithCertificate(certificate);
            }

            if (!string.IsNullOrEmpty(redirectUri))
            {
                builder = builder.WithRedirectUri(redirectUri);
            }

            if (!string.IsNullOrEmpty(tenantId))
            {
                builder = builder.WithTenantId(tenantId);
            }

            IConfidentialClientApplication client = builder.WithLogging((level, message, pii) =>
            {
                PartnerSession.Instance.DebugMessages.Enqueue($"[MSAL] {level} {message}");
            }).Build();

            if (PartnerSession.Instance.TryGetComponent(ComponentKey.TokenCache, out IPartnerTokenCache tokenCache))
            {
                tokenCache.RegisterCache(client);
            }

            return(client);
        }
        /// <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);
        }
Exemple #19
0
        public static string GetToken(HttpContext httpContext)
        {
            string response;

            try
            {
                // Retrieve the token with the specified scopes
                string[] scope          = _options["Scopes"].Split(' ');
                string   signedInUserID = httpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;

                IConfidentialClientApplication cca =
                    ConfidentialClientApplicationBuilder.Create(_options["ClientId"])
                    .WithClientSecret(_options["ClientSecret"])
                    .WithB2CAuthority("https://emsfiiot.b2clogin.com/tfp/emsfiiot.onmicrosoft.com/B2C_1_Signin/v2.0")
                    .Build();
                ITokenCache cache = new MSALStaticCache(signedInUserID, httpContext).EnablePersistence(cca.UserTokenCache);

                IEnumerable <IAccount> accounts     = cca.GetAccountsAsync().Result;
                AuthenticationResult   tokenRequest = cca.AcquireTokenSilent(scope, accounts.FirstOrDefault()).ExecuteAsync().Result;

                if (tokenRequest.AccessToken != null)
                {
                    httpContext.Response.Cookies.Append("ADB2CToken",
                                                        tokenRequest.AccessToken,
                                                        new CookieOptions
                    {
                        Expires = tokenRequest.ExpiresOn
                    });
                }

                response = tokenRequest.AccessToken;
            }
            catch (MsalUiRequiredException ex)
            {
                response = $"Session has expired. Please sign in again. {ex.Message}";
                httpContext.Response.Redirect("/Account/SignIn");
            }
            catch (Exception ex)
            {
                response = $"Error calling API: {ex.Message}";
            }

            return(response);
        }
Exemple #20
0
        private async Task <AuthenticationResult?> GetAuthenticationResultForWebApiToCallDownstreamApiAsync(
            IConfidentialClientApplication application,
            string authority,
            IEnumerable <string> scopes,
            TokenAcquisitionOptions?tokenAcquisitionOptions)
        {
            try
            {
                // In web API, validatedToken will not be null
                JwtSecurityToken?validatedToken = CurrentHttpContext?.GetTokenUsedToCallWebAPI();

                // Case of web APIs: we need to do an on-behalf-of flow, with the token used to call the API
                if (validatedToken != null)
                {
                    // In the case the token is a JWE (encrypted token), we use the decrypted token.
                    string tokenUsedToCallTheWebApi = validatedToken.InnerToken == null ? validatedToken.RawData
                                                : validatedToken.InnerToken.RawData;
                    var builder = application
                                  .AcquireTokenOnBehalfOf(
                        scopes.Except(_scopesRequestedByMsal),
                        new UserAssertion(tokenUsedToCallTheWebApi))
                                  .WithSendX5C(_microsoftIdentityOptions.SendX5C)
                                  .WithAuthority(authority);

                    if (tokenAcquisitionOptions != null)
                    {
                        builder.WithExtraQueryParameters(tokenAcquisitionOptions.ExtraQueryParameters);
                        builder.WithCorrelationId(tokenAcquisitionOptions.CorrelationId);
                        builder.WithForceRefresh(tokenAcquisitionOptions.ForceRefresh);
                        builder.WithClaims(tokenAcquisitionOptions.Claims);
                    }

                    return(await builder.ExecuteAsync()
                           .ConfigureAwait(false));
                }

                return(null);
            }
            catch (MsalUiRequiredException ex)
            {
                _logger.LogInformation(string.Format(CultureInfo.InvariantCulture, LogMessages.ErrorAcquiringTokenForDownstreamWebApi, ex.Message));
                throw;
            }
        }
Exemple #21
0
        public async Task TokensAreInterchangable_Regional_To_NonRegional_Async()
        {
            using (var httpManager = new MockHttpManager())
            {
                httpManager.AddRegionDiscoveryMockHandler(TestConstants.Region);
                httpManager.AddMockHandler(CreateTokenResponseHttpHandler(true));

                IConfidentialClientApplication appWithRegion = CreateCca(
                    httpManager,
                    ConfidentialClientApplication.AttemptRegionDiscovery);
                InMemoryTokenCache memoryTokenCache = new InMemoryTokenCache();
                memoryTokenCache.Bind(appWithRegion.AppTokenCache);

                IConfidentialClientApplication appWithoutRegion = CreateCca(
                    httpManager,
                    null);
                memoryTokenCache.Bind(appWithoutRegion.AppTokenCache);

                AuthenticationResult result = await appWithRegion
                                              .AcquireTokenForClient(TestConstants.s_scope)
                                              .ExecuteAsync(CancellationToken.None)
                                              .ConfigureAwait(false);

                Assert.AreEqual(TestConstants.Region, result.ApiEvent.RegionUsed);
                Assert.AreEqual((int)RegionSource.Imds, result.ApiEvent.RegionSource);
                Assert.AreEqual(null, result.ApiEvent.UserProvidedRegion);
                Assert.AreEqual(false, result.ApiEvent.IsValidUserProvidedRegion);
                Assert.AreEqual(false, result.ApiEvent.FallbackToGlobal);

                // when switching to non-region, token is found in the cache
                result = await appWithoutRegion
                         .AcquireTokenForClient(TestConstants.s_scope)
                         .ExecuteAsync(CancellationToken.None)
                         .ConfigureAwait(false);

                Assert.AreEqual(null, result.ApiEvent.RegionUsed);
                Assert.AreEqual((int)RegionSource.None, result.ApiEvent.RegionSource);
                Assert.AreEqual(null, result.ApiEvent.UserProvidedRegion);
                Assert.AreEqual(null, result.ApiEvent.IsValidUserProvidedRegion);
                Assert.AreEqual(null, result.ApiEvent.FallbackToGlobal);

                Assert.IsTrue(result.AuthenticationResultMetadata.TokenSource == TokenSource.Cache);
            }
        }
        /// <summary>
        /// Get Access token
        /// </summary>
        /// <returns>Access token</returns>
        public static async Task <string> GetAccessToken()
        {
            AuthenticationResult authenticationResult = null;

            if (ConfigValidatorService.AuthenticationType.Equals("masteruser", StringComparison.InvariantCultureIgnoreCase))
            {
                IPublicClientApplication clientApp = PublicClientApplicationBuilder
                                                     .Create(ConfigValidatorService.ApplicationId)
                                                     .WithAuthority(m_authorityUrl)
                                                     .Build();
                var userAccounts = await clientApp.GetAccountsAsync();

                try
                {
                    authenticationResult = await clientApp.AcquireTokenSilent(m_scope, userAccounts.FirstOrDefault()).ExecuteAsync();
                }
                catch (MsalUiRequiredException)
                {
                    SecureString secureStringPassword = new SecureString();
                    foreach (var key in ConfigValidatorService.Password)
                    {
                        secureStringPassword.AppendChar(key);
                    }
                    authenticationResult = await clientApp.AcquireTokenByUsernamePassword(m_scope, ConfigValidatorService.Username, secureStringPassword).ExecuteAsync();
                }
            }

            // Service Principal auth is recommended by Microsoft to achieve App Owns Data Power BI embedding
            else if (ConfigValidatorService.AuthenticationType.Equals("serviceprincipal", StringComparison.InvariantCultureIgnoreCase))
            {
                // For app only authentication, we need the specific tenant id in the authority url
                var tenantSpecificURL = m_authorityUrl.Replace("organizations", ConfigValidatorService.Tenant);

                IConfidentialClientApplication clientApp = ConfidentialClientApplicationBuilder
                                                           .Create(ConfigValidatorService.ApplicationId)
                                                           .WithClientSecret(ConfigValidatorService.ApplicationSecret)
                                                           .WithAuthority(tenantSpecificURL)
                                                           .Build();

                authenticationResult = await clientApp.AcquireTokenForClient(m_scope).ExecuteAsync();
            }

            return(authenticationResult.AccessToken);
        }
Exemple #23
0
        private static async Task RunAsync()
        {
            AuthenticationConfig config = AuthenticationConfig.ReadFromJsonFile("appsettings.json");

            IConfidentialClientApplication app = ConfidentialClientApplicationBuilder.Create(config.ClientId)
                                                 .WithClientSecret(config.ClientSecret)
                                                 .WithAuthority(new Uri($"https://login.windows.net/{config.Tenant}"))
                                                 .Build();

            string[] scopes = new string[] { $"{config.ApiUrl}/.default" };  //make sure the configured scope as string reads as follows (double slash): https://api.timeseries.azure.com//.default


            AuthenticationResult result = null;

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

                Console.ForegroundColor = ConsoleColor.Green;
                if (!string.IsNullOrEmpty(result.AccessToken))
                {
                    Console.WriteLine("JWT token acquired.");
                }
                Console.ResetColor();
            }
            catch (MsalServiceException ex) when(ex.Message.Contains("AADSTS70011"))
            {
                // Invalid scope. The scope has to be of the form "https://resourceurl/.default"
                // Mitigation: change the scope to be as expected
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Scope provided is not supported");
                Console.ResetColor();
            }

            if (result != null)
            {
                var httpClient = new HttpClient();
                var apiCaller  = new ProtectedApiCallHelper(httpClient);

                //See for other APIs: https://docs.microsoft.com/en-us/rest/api/time-series-insights/reference-data-access-overview
                await apiCaller.CallWebApiAndProcessResultASync($"{config.TsiEnvironmentBaseUrl}timeseries/modelSettings?api-version=2020-07-31", result.AccessToken, Display);
            }
        }
        public MsalService(IConfiguration Configuration, IHttpContextAccessor UserHttpContext)
        {
            this.Configuration   = Configuration;
            this.UserHttpContext = UserHttpContext;

            ClientId     = Configuration["AzureAd:ClientId"];
            Authority    = $"{Configuration["AzureAd:Instance"]}{Configuration["AzureAd:TenantId"]}";
            ClientSecret = Configuration["AzureAd:ClientSecret"];

            var CallbackPath = Configuration["AzureAd:CallbackPath"];

            RedirectUri = $"{UserHttpContext.HttpContext.Request.Scheme}://{UserHttpContext.HttpContext.Request.Host}{CallbackPath}";

            client = ConfidentialClientApplicationBuilder.Create(ClientId)
                     .WithAuthority(Authority)
                     .WithRedirectUri(RedirectUri)
                     .WithClientSecret(ClientSecret)
                     .Build();
        }
        /// <summary>
        /// Gets an access token for a downstream API on behalf of the user whose account is passed as an argument.
        /// </summary>
        /// <param name="application"><see cref="IConfidentialClientApplication"/>.</param>
        /// <param name="account">User IAccount for which to acquire a token.
        /// See <see cref="Microsoft.Identity.Client.AccountId.Identifier"/>.</param>
        /// <param name="scopes">Scopes for the downstream API to call.</param>
        /// <param name="authority">Authority based on a specific tenant for which to acquire a token to access the scopes
        /// on behalf of the user.</param>
        /// <param name="userFlow">Azure AD B2C user flow.</param>
        /// <param name="tokenAcquisitionOptions">Options passed-in to create the token acquisition object which calls into MSAL .NET.</param>
        private async Task <AuthenticationResult> GetAuthenticationResultForWebAppWithAccountFromCacheAsync(
            IConfidentialClientApplication application,
            IAccount?account,
            IEnumerable <string> scopes,
            string?authority,
            string?userFlow = null,
            TokenAcquisitionOptions?tokenAcquisitionOptions = null)
        {
            if (scopes == null)
            {
                throw new ArgumentNullException(nameof(scopes));
            }

            var builder = application
                          .AcquireTokenSilent(scopes.Except(_scopesRequestedByMsal), account)
                          .WithSendX5C(_microsoftIdentityOptions.SendX5C);

            if (tokenAcquisitionOptions != null)
            {
                builder.WithExtraQueryParameters(tokenAcquisitionOptions.ExtraQueryParameters);
                builder.WithCorrelationId(tokenAcquisitionOptions.CorrelationId);
                builder.WithForceRefresh(tokenAcquisitionOptions.ForceRefresh);
                builder.WithClaims(tokenAcquisitionOptions.Claims);
            }

            // Acquire an access token as a B2C authority
            if (_microsoftIdentityOptions.IsB2C)
            {
                string b2cAuthority = application.Authority.Replace(
                    new Uri(application.Authority).PathAndQuery,
                    $"/{ClaimConstants.Tfp}/{_microsoftIdentityOptions.Domain}/{userFlow ?? _microsoftIdentityOptions.DefaultUserFlow}");

                builder.WithB2CAuthority(b2cAuthority)
                .WithSendX5C(_microsoftIdentityOptions.SendX5C);
            }
            else
            {
                builder.WithAuthority(authority);
            }

            return(await builder.ExecuteAsync()
                   .ConfigureAwait(false));
        }
        /// <summary>
        /// Common method to remove the cached tokens for the currently signed in user
        /// </summary>
        /// <returns></returns>
        public static async Task ClearUserTokenCache()
        {
            IConfidentialClientApplication clientapp = ConfidentialClientApplicationBuilder.Create(B2C_Globals.ClientId)
                                                       .WithB2CAuthority(B2C_Globals.Authority)
                                                       .WithClientSecret(B2C_Globals.ClientSecret)
                                                       .WithRedirectUri(B2C_Globals.RedirectUri)
                                                       .Build();

            // We only clear the user's tokens.
            MSALPerUserMemoryTokenCache userTokenCache = new MSALPerUserMemoryTokenCache(clientapp.UserTokenCache);
            var userAccounts = await clientapp.GetAccountsAsync();

            foreach (var account in userAccounts)
            {
                //Remove the users from the MSAL's internal cache
                await clientapp.RemoveAsync(account);
            }
            userTokenCache.Clear();
        }
Exemple #27
0
        public async Task <string> GetAuthToken()
        {
            if (Mode == RecordedTestMode.Playback)
            {
                return("auth token");
            }

            IConfidentialClientApplication application = ConfidentialClientApplicationBuilder.Create(TestConfigOAuth.ActiveDirectoryApplicationId)
                                                         .WithAuthority(AzureCloudInstance.AzurePublic, TestConfigOAuth.ActiveDirectoryTenantId)
                                                         .WithClientSecret(TestConfigOAuth.ActiveDirectoryApplicationSecret)
                                                         .Build();

            string[] scopes = new string[] { "https://storage.azure.com/.default" };

            AcquireTokenForClientParameterBuilder result = application.AcquireTokenForClient(scopes);
            AuthenticationResult authenticationResult    = await result.ExecuteAsync();

            return(authenticationResult.AccessToken);
        }
        /// <summary>
        /// Builds the confidential client application.
        /// </summary>
        /// <param name="currentUser">The current user.</param>
        /// <returns></returns>
        public static IConfidentialClientApplication BuildConfidentialClientApplication(ClaimsPrincipal currentUser)
        {
            var principal = currentUser ?? ClaimsPrincipal.Current;

            IConfidentialClientApplication clientApplication = ConfidentialClientApplicationBuilder
                                                               .Create(VeracityIntegrationOptions.ClientId)
                                                               .WithClientSecret(VeracityIntegrationOptions.ClientSecret)
                                                               .WithRedirectUri(VeracityIntegrationOptions.RedirectUri)
                                                               .WithAuthority(new Uri(VeracityIntegrationOptions.Authority))
                                                               .Build();

            if (principal != null)
            {
                // After the ConfidentialClientApplication is created, we overwrite its default UserTokenCache with our implementation
                MSALPerUserMemoryTokenCache userTokenCache = new MSALPerUserMemoryTokenCache(clientApplication.UserTokenCache, principal);
            }

            return(clientApplication);
        }
Exemple #29
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>
        /// Acquires a token from the authority configured in the app, for the confidential client itself (not on behalf of a user)
        /// using the client credentials flow. See https://aka.ms/msal-net-client-credentials.
        /// </summary>
        /// <param name="scopes">scopes requested to access a protected API. For this flow (client credentials), the scopes
        /// should be of the form "{ResourceIdUri/.default}" for instance <c>https://management.azure.net/.default</c> or, for Microsoft
        /// Graph, <c>https://graph.microsoft.com/.default</c> as the requested scopes are defined statically with the application registration
        /// in the portal, and cannot be overriden in the application.</param>
        /// <returns>An access token for the app itself, based on its scopes.</returns>
        public async Task <string> GetAccessTokenForAppAsync(IEnumerable <string> scopes)
        {
            if (scopes == null)
            {
                throw new ArgumentNullException(nameof(scopes));
            }

            // Use MSAL to get the right token to call the API
            _application = await GetOrBuildConfidentialClientApplicationAsync().ConfigureAwait(false);

            AuthenticationResult result;

            result = await _application
                     .AcquireTokenForClient(scopes.Except(_scopesRequestedByMsal))
                     .ExecuteAsync()
                     .ConfigureAwait(false);

            return(result.AccessToken);
        }