/// <summary>
        /// Tries to acquire an application Microsoft Graph Access Token
        /// </summary>
        /// <param name="tenant">Name of the tenant to acquire the token for (i.e. contoso.onmicrosoft.com). Required.</param>
        /// <param name="clientId">ClientId to use to acquire the token. Required.</param>
        /// <param name="certificate">Certificate to use to acquire the token. Required.</param>
        /// <returns><see cref="GraphToken"/> instance with the token</returns>
        public static GenericToken AcquireApplicationToken(string tenant, string clientId, X509Certificate2 certificate)
        {
            if (string.IsNullOrEmpty(tenant))
            {
                throw new ArgumentNullException(nameof(tenant));
            }
            if (string.IsNullOrEmpty(clientId))
            {
                throw new ArgumentNullException(nameof(clientId));
            }
            if (certificate == null)
            {
                throw new ArgumentNullException(nameof(certificate));
            }
            AuthenticationResult tokenResult = null;

            if (confidentialClientApplication == null)
            {
                confidentialClientApplication = ConfidentialClientApplicationBuilder.Create(clientId).WithAuthority($"{OAuthBaseUrl}{tenant}").WithCertificate(certificate).Build();
            }

            var account = confidentialClientApplication.GetAccountsAsync().GetAwaiter().GetResult();

            try
            {
                tokenResult = confidentialClientApplication.AcquireTokenSilent(new[] { $"{ResourceIdentifier}/{DefaultScope}" }, account.First()).ExecuteAsync().GetAwaiter().GetResult();
            }
            catch
            {
                tokenResult = confidentialClientApplication.AcquireTokenForClient(new[] { $"{ResourceIdentifier}/{DefaultScope}" }).ExecuteAsync().GetAwaiter().GetResult();
            }

            return(new GraphToken(tokenResult.AccessToken));
        }
Beispiel #2
0
        public static GenericToken AcquireApplicationToken(string tenant, string clientId, string authority, string[] scopes, X509Certificate2 certificate)
        {
            if (string.IsNullOrEmpty(tenant))
            {
                throw new ArgumentNullException(nameof(tenant));
            }
            if (string.IsNullOrEmpty(clientId))
            {
                throw new ArgumentNullException(nameof(clientId));
            }
            if (certificate == null)
            {
                throw new ArgumentNullException(nameof(certificate));
            }
            AuthenticationResult tokenResult = null;

            if (confidentialClientApplication == null)
            {
                confidentialClientApplication = ConfidentialClientApplicationBuilder.Create(clientId).WithAuthority(authority).WithCertificate(certificate).Build();
            }

            var account = confidentialClientApplication.GetAccountsAsync().GetAwaiter().GetResult();

            try
            {
                tokenResult = confidentialClientApplication.AcquireTokenSilent(scopes, account.First()).ExecuteAsync().GetAwaiter().GetResult();
            }
            catch
            {
                tokenResult = confidentialClientApplication.AcquireTokenForClient(scopes).ExecuteAsync().GetAwaiter().GetResult();
            }

            return(new GenericToken(tokenResult.AccessToken));
        }
Beispiel #3
0
        /// <summary>
        /// Get Azure Active Directory token
        /// </summary>
        /// <returns>Azure Active Directory token</returns>
        public async Task <string> GetAadToken(string[] scopes)
        {
            var clientCertificate = new X509Certificate2(Convert.FromBase64String(base64Certificate), string.Empty, X509KeyStorageFlags.MachineKeySet);
            var authorityUrl      = $"https://login.microsoftonline.com/{aadConfig.Value.TenantId}";

            IConfidentialClientApplication clientApp = ConfidentialClientApplicationBuilder
                                                       .Create(aadConfig.Value.ClientId)
                                                       .WithCertificate(clientCertificate)
                                                       .WithAuthority(authorityUrl)
                                                       .Build();

            // Initialize cache to save AAD Token
            new MSALMemoryTokenCache(clientApp.AppTokenCache);
            AuthenticationResult authenticationResult = await clientApp.AcquireTokenForClient(scopes).ExecuteAsync();

            // Get tokenExpiry to check if near expiration
            var tokenExpiry = authenticationResult.ExpiresOn.DateTime;

            // Refresh the AAD token when near expiration
            if (tokenExpiry.Subtract(DateTime.UtcNow) <= TimeSpan.FromMinutes(Constant.RenewBeforeMinutes))
            {
                authenticationResult = await clientApp.AcquireTokenForClient(scopes).WithForceRefresh(true).ExecuteAsync();
            }

            // Get the AAD token from the result
            var aadToken = authenticationResult.AccessToken;

            return(aadToken);
        }
        public async Task <string> CreateUserIntoActiveDirectory(string name, string email)
        {
            var scopes     = new string[] { "https://graph.microsoft.com/.default" };
            var authResult = await _confidentialClientApplication.AcquireTokenForClient(scopes).ExecuteAsync();

            var graphServiceClient = new GraphServiceClient(new DelegateAuthenticationProvider(async(requestMessage) =>
                                                                                               requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken)));
            var invitation = new Invitation {
                InvitedUserDisplayName  = name,
                InvitedUserEmailAddress = email,
                InvitedUserMessageInfo  = new InvitedUserMessageInfo()
                {
                    CustomizedMessageBody = "Bienvenido(a) a la plataforma agrícola", MessageLanguage = "es-es"
                },
                InviteRedirectUrl     = "https://aresa.trifenix.io",
                SendInvitationMessage = true,
            };
            await graphServiceClient.Invitations.Request().AddAsync(invitation);

            string objectId = String.Empty;

            do
            {
                Thread.Sleep(1000);
                objectId = await GetObjectIdFromEmail(email);
            } while (String.IsNullOrEmpty(objectId));
            return(objectId);
        }
        public async Task UserRegion_DiscoveryHappensOnce_Async()
        {
            using (var httpManager = new MockHttpManager())
            {
                httpManager.AddRegionDiscoveryMockHandler(TestConstants.Region);
                httpManager.AddMockHandler(CreateTokenResponseHttpHandler(true));

                IConfidentialClientApplication app = CreateCca(
                    httpManager,
                    TestConstants.Region);

                AuthenticationResult result = await app
                                              .AcquireTokenForClient(TestConstants.s_scope)
                                              .ExecuteAsync()
                                              .ConfigureAwait(false);

                Assert.AreEqual(TestConstants.Region, result.ApiEvent.RegionUsed);
                Assert.AreEqual((int)RegionAutodetectionSource.Imds, result.ApiEvent.RegionAutodetectionSource);
                Assert.AreEqual((int)RegionOutcome.UserProvidedValid, result.ApiEvent.RegionOutcome);

                Assert.IsTrue(result.AuthenticationResultMetadata.TokenSource == TokenSource.IdentityProvider);

                result = await app
                         .AcquireTokenForClient(TestConstants.s_scope)
                         .ExecuteAsync()
                         .ConfigureAwait(false);

                Assert.IsTrue(result.AuthenticationResultMetadata.TokenSource == TokenSource.Cache);
            }
        }
        public async Task <AuthenticationResult> AcquireMicrosoftGraphAuthenticationResultAsync(
            CancellationToken cancellationToken = default
            )
        {
            var authenticationResult = await _confidentialClientApplication
                                       .AcquireTokenForClient(MicrosoftGraphIAIScopes)
                                       .ExecuteAsync(cancellationToken);

            return(authenticationResult);
        }
        public static GenericToken AcquireApplicationToken(string tenant, string clientId, string authority, string[] scopes, X509Certificate2 certificate)
        {
            if (string.IsNullOrEmpty(tenant))
            {
                throw new ArgumentNullException(nameof(tenant));
            }
            if (string.IsNullOrEmpty(clientId))
            {
                throw new ArgumentNullException(nameof(clientId));
            }
            if (certificate == null)
            {
                throw new ArgumentNullException(nameof(certificate));
            }
            AuthenticationResult tokenResult = null;

            if (confidentialClientApplication == null)
            {
                confidentialClientApplication = ConfidentialClientApplicationBuilder.Create(clientId).WithAuthority(authority).WithCertificate(certificate).Build();
            }

            var account = confidentialClientApplication.GetAccountsAsync().GetAwaiter().GetResult();

            try
            {
                tokenResult = confidentialClientApplication.AcquireTokenSilent(scopes, account.First()).WithForceRefresh(true).ExecuteAsync().GetAwaiter().GetResult();
            }
            catch
            {
                try
                {
                    tokenResult = confidentialClientApplication.AcquireTokenForClient(scopes).ExecuteAsync().GetAwaiter().GetResult();
                }
                catch (MsalUiRequiredException msalEx)
                {
                    if (msalEx.Classification == UiRequiredExceptionClassification.ConsentRequired)
                    {
                        if (clientId == PnPConnection.PnPManagementShellClientId)
                        {
                            throw new PSInvalidOperationException("Please provide consent to the PnP Management Shell application with 'Register-PnPManagementShellAccess'");
                        }
                        else
                        {
                            throw msalEx;
                        }
                    }
                }
            }

            return(new GenericToken(tokenResult.AccessToken));
        }
Beispiel #8
0
        private async Task RunClientCredsAsync(Cloud cloud, CredentialType credentialType, bool UseAppIdUri = false, bool sendX5C = false)
        {
            Trace.WriteLine($"Running test with settings for cloud {cloud}, credential type {credentialType}");
            IConfidentialAppSettings settings = ConfidentialAppSettings.GetSettings(cloud);

            settings.UseAppIdUri = UseAppIdUri;

            AuthenticationResult authResult;

            IConfidentialClientApplication confidentialApp = CreateApp(credentialType, settings, sendX5C);
            var  appCacheRecorder = confidentialApp.AppTokenCache.RecordAccess();
            Guid correlationId    = Guid.NewGuid();

            authResult = await confidentialApp
                         .AcquireTokenForClient(settings.AppScopes)
                         .WithCorrelationId(correlationId)
                         .ExecuteAsync(CancellationToken.None)
                         .ConfigureAwait(false);

            MsalAssert.AssertAuthResult(authResult);
            appCacheRecorder.AssertAccessCounts(1, 1);
            Assert.AreEqual(TokenSource.IdentityProvider, authResult.AuthenticationResultMetadata.TokenSource);
            Assert.IsTrue(appCacheRecorder.LastAfterAccessNotificationArgs.IsApplicationCache);
            Assert.IsTrue(appCacheRecorder.LastAfterAccessNotificationArgs.HasTokens);
            Assert.AreEqual(correlationId, appCacheRecorder.LastAfterAccessNotificationArgs.CorrelationId);
            Assert.AreEqual(correlationId, appCacheRecorder.LastBeforeAccessNotificationArgs.CorrelationId);
            Assert.IsTrue(authResult.AuthenticationResultMetadata.DurationTotalInMs > 0);
            Assert.IsTrue(authResult.AuthenticationResultMetadata.DurationInHttpInMs > 0);
            Assert.AreEqual(
                GetExpectedCacheKey(settings.ClientId, settings.TenantId),
                appCacheRecorder.LastAfterAccessNotificationArgs.SuggestedCacheKey);

            // Call again to ensure token cache is hit
            authResult = await confidentialApp
                         .AcquireTokenForClient(settings.AppScopes)
                         .ExecuteAsync()
                         .ConfigureAwait(false);

            MsalAssert.AssertAuthResult(authResult);
            Assert.IsTrue(authResult.AuthenticationResultMetadata.DurationInHttpInMs == 0);

            appCacheRecorder.AssertAccessCounts(2, 1);
            Assert.AreEqual(TokenSource.Cache, authResult.AuthenticationResultMetadata.TokenSource);
            Assert.IsTrue(appCacheRecorder.LastAfterAccessNotificationArgs.IsApplicationCache);
            Assert.IsTrue(appCacheRecorder.LastAfterAccessNotificationArgs.HasTokens);
            Assert.AreNotEqual(correlationId, appCacheRecorder.LastAfterAccessNotificationArgs.CorrelationId);
            Assert.AreNotEqual(correlationId, appCacheRecorder.LastBeforeAccessNotificationArgs.CorrelationId);
            Assert.AreEqual(
                GetExpectedCacheKey(settings.ClientId, settings.TenantId),
                appCacheRecorder.LastAfterAccessNotificationArgs.SuggestedCacheKey);
        }
        /// <summary>
        /// Acquires an access token from the app registration.
        /// </summary>
        /// <param name="app">The app configured with client secrets and authority.</param>
        /// <returns>The access token for authorization.</returns>
        private static async Task <string> AcquireAccessTokenAsync(IConfidentialClientApplication app)
        {
            // With client credentials flows, the scope is always of the shape "resource/.default" because the
            // application permissions need to be set statically (in the portal or by PowerShell), and then granted by
            // a tenant administrator.
            var scopes = new string[] { "38c77d00-5fcb-4cce-9d93-af4738258e3c/.default" };

            AuthenticationResult result;

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

                return(result.AccessToken);
            }
            catch (MsalUiRequiredException)
            {
                // The application doesn't have sufficient permissions.
                // - Did you declare enough app permissions during app creation?
                // - Did the tenant admin grant permissions to the application?
                throw;
            }
            catch (MsalServiceException ex) when(ex.Message.Contains("AADSTS70011"))
            {
                // Invalid scope. The scope has to be in the form "https://resourceurl/.default"
                // Mitigation: Change the scope to be as expected.
                throw;
            }
        }
Beispiel #10
0
        private async Task <string> GetAccessToken()
        {
            if (_token is null)
            {
                try
                {
                    var authResult = await _app
                                     .AcquireTokenForClient(_config.Scopes)
                                     .ExecuteAsync();

                    _token = authResult.AccessToken;

                    return(_token);
                }
                catch (Exception)
                {
                    return(null);
                    // ! actually we need to throw some kind of error here
                }
            }
            else
            {
                return(_token);
            }
        }
Beispiel #11
0
        /// <summary>
        /// Generate a Bearer token for accessing the Kusto resource using MSAL
        /// </summary>
        /// <returns>The authentication result</returns>
        private async Task <AuthenticationResult> GenerateKustoToken()
        {
            // Define the resource scope to be the current Kusto cluster
            string[] scopes = { $"https://{this.KustoClusterName}.kusto.windows.net/.default" };

            // Authenticate with AAD App credentials
            BuildContext();

            AuthenticationResult result;

            // Acquire token using MSAL
            try
            {
                result = await Context.AcquireTokenForClient(scopes).ExecuteAsync();
            }
            catch (Exception ex)
            {
                var errorMsg = $"Exception: {ex.Message}";
                if (ex.InnerException != null)
                {
                    errorMsg += $" InnerException: {ex.InnerException.Message}";
                }
                throw new Exception($"There was an error while acquiring Kusto authorization Token with client ID/secret authentication. {errorMsg}");
            }

            if (result == null || result.CreateAuthorizationHeader() == null)
            {
                throw new Exception
                          ("Received invalid Kusto authentication result. " +
                          "The result might be null, or missing HTTP authorization header from the authentication result.");
            }
            return(result);
        }
        private async Task ApiCall(string url)
        {
            try
            {
                IConfidentialClientApplication confidentialClientApplication =
                    ConfidentialClientApplicationBuilder
                    .Create(Configuration["AzureAd:ClientId"])
                    .WithTenantId(Configuration["AzureAd:TenantId"])
                    .WithClientSecret(Configuration["AzureAd:ClientSecret"])
                    .Build();
                string[]             scopes = new string[] { "https://graph.microsoft.com/.default" };
                AuthenticationResult result = null;
                result = await confidentialClientApplication.AcquireTokenForClient(scopes)
                         .ExecuteAsync();

                var httpClient = new HttpClient();
                var apiCaller  = new ProtectedApiCallHelper(httpClient);
                var res        = await apiCaller
                                 .CallWebApiAndProcessResultASync(
                    url,
                    result.AccessToken
                    );

                ProcessGraphUsers(res);
                if (res.Properties().FirstOrDefault(p => p.Name == "@odata.nextLink") != null)
                {
                    await ApiCall(res.Properties().First(p => p.Name == "@odata.nextLink").Value.ToString());
                }
            }
            catch (Exception ex)
            {
                Telemetry.TrackException(ex);
                ToastService.ShowWarning("Fout bij het ophalen van de gebruikers.");
            }
        }
        public async Task FetchRegionFromEnvironmentAsync()
        {
            using (var httpManager = new MockHttpManager())
            {
                try
                {
                    Environment.SetEnvironmentVariable("REGION_NAME", TestConstants.Region);
                    IConfidentialClientApplication app = CreateCca(
                        httpManager,
                        ConfidentialClientApplication.AttemptRegionDiscovery);

                    httpManager.AddMockHandler(CreateTokenResponseHttpHandler(true));

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

                    Assert.AreEqual(TestConstants.Region, result.ApiEvent.RegionUsed);
                    Assert.AreEqual((int)RegionAutodetectionSource.EnvVariable, result.ApiEvent.RegionAutodetectionSource);
                    Assert.AreEqual((int)RegionOutcome.AutodetectSuccess, result.ApiEvent.RegionOutcome);

                    Assert.IsNotNull(result.AccessToken);
                }
                finally
                {
                    Environment.SetEnvironmentVariable("REGION_NAME", null);
                }
            }
        }
Beispiel #14
0

        
        public async Task <string> GetAccessToken()
        {
            string[] scopes = new string[] { $"{config.ApiUrl}.default" };
            // If there is no saved user account, the user must sign-in
            //if (!string.IsNullOrEmpty(_token))
            //    return _token;

            try
            {
                // Invoke device code flow so user can sign-in with a browser
                var result = await _msalClient.AcquireTokenForClient(scopes)
                             .ExecuteAsync();

                //Console.ForegroundColor = ConsoleColor.Green;
                //Console.WriteLine("Token acquired");
                //Console.ResetColor();

                //_token = result.AccessToken;
                return(result.AccessToken);
            }
            catch (Exception exception)
            {
                Console.WriteLine($"Error getting access token: {exception.Message}");
                return(null);
            }
        }
Beispiel #17
0
        async Task ClientCredentialsCertScenario()
        {
            X509Certificate2 certificate = GetCertificate();

            AzureActiveDirectoryTokenProvider.AuthenticationCallback authCallback = async(audience, authority, state) =>
            {
                IConfidentialClientApplication app = ConfidentialClientApplicationBuilder.Create(ClientId)
                                                     .WithAuthority(authority)
                                                     .WithCertificate(certificate)
                                                     .Build();

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

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

                return(authResult.AccessToken);
            };

            QueueClient qc = QueueClient.CreateWithAzureActiveDirectory(
                new Uri($"sb://{ServiceBusNamespace}/"),
                QueueName,
                authCallback,
                $"https://login.windows.net/{TenantId}");

            await SendReceiveAsync(qc);
        }
        public async Task Run([TimerTrigger("%FunctionTimer%")] TimerInfo myTimer, ILogger log)
        {
            log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
            var result = await _app.AcquireTokenForClient(new[] { $"{_productApiSettings.ScopeUri}/.default" }).ExecuteAsync();

            var token = result.AccessToken;

            _productClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(Constants.Bearer, token);

            var productResult = await _productClient.GetAsync(_productApiSettings.Url);

            if (!productResult.IsSuccessStatusCode)
            {
                log.LogError($"Product Result failes with response {productResult.ReasonPhrase}");
                return;
            }

            var content = await productResult.Content.ReadAsStringAsync();

            var products = JsonConvert.DeserializeObject <List <Product> >(content);

            foreach (var item in products)
            {
                log.LogInformation($"Product Name: {item.Name}");
                log.LogInformation($"Product Price: {item.Price}");
                log.LogInformation($"Product quantity: {item.AvailableQuantity}");
                log.LogInformation("---------------------------------------------");
            }
        }
Beispiel #19
0
        private static void CreateAuthorizationProvider(IConfigurationRoot appInformation)
        {
            var clientId     = appInformation["applicationId"];
            var tenantId     = appInformation["tenantId"];
            var clientSecret = appInformation["applicationSecret"];
            var redirectUri  = appInformation["redirectUri"];

            IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
                                                                           .Create(clientId)
                                                                           .WithAuthority(authorityUri: $"https://login.microsoftonline.com/{tenantId}/v2.0")
                                                                           .WithClientSecret(clientSecret)
                                                                           .WithRedirectUri(redirectUri)
                                                                           .Build();

            ClientCredentialProvider authenticationProvider = new ClientCredentialProvider(confidentialClientApplication);

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

            _graphServiceClient =
                new GraphServiceClient(new DelegateAuthenticationProvider(async(requestMessage) => {
                var authResult = await confidentialClientApplication
                                 .AcquireTokenForClient(scopes)
                                 .ExecuteAsync();
                requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
            })
                                       );
        }
        private TokenProvider createTokenProvider()
        {
            if (_config.IsOnPrem)
            {
                X509Certificate2 cert = getCertificateBySubject(_config.CertificateSubject);
                var auth          = string.Format(CultureInfo.InvariantCulture, AAD, _config.TenantName);
                var tokenProvider = TokenProvider.CreateAzureActiveDirectoryTokenProvider(async(audience, authority, state) =>
                {
                    IConfidentialClientApplication app = ConfidentialClientApplicationBuilder.Create(_config.AadClientId)
                                                         .WithAuthority(authority)
                                                         .WithCertificate(cert)
                                                         .Build();

                    var serviceBusAudience = new Uri(ServiceBusAudience);

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

                return(tokenProvider);
            }
            else
            {
                return(TokenProvider.CreateManagedIdentityTokenProvider());
            }
        }
        public async Task RegionFallbackToGlobalAsync()
        {
            using (var httpManager = new MockHttpManager())
            {
                httpManager.AddRegionDiscoveryMockHandlerNotFound();
                httpManager.AddInstanceDiscoveryMockHandler();
                httpManager.AddMockHandler(CreateTokenResponseHttpHandler(false));

                IConfidentialClientApplication app = CreateCca(
                    httpManager,
                    ConfidentialClientApplication.AttemptRegionDiscovery);

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

                    Assert.IsNotNull(result.AccessToken);

                    Assert.AreEqual(null, result.ApiEvent.RegionUsed);
                    Assert.AreEqual((int)RegionAutodetectionSource.FailedAutoDiscovery, result.ApiEvent.RegionAutodetectionSource);
                    Assert.AreEqual((int)RegionOutcome.FallbackToGlobal, result.ApiEvent.RegionOutcome);
                }
                catch (MsalServiceException)
                {
                    Assert.Fail("Fallback to global failed.");
                }
            }
        }
Beispiel #22
0
        /// <summary>
        /// Gets an access token for the requested resource and scope
        /// </summary>
        /// <param name="resource">Resource to request an access token for (unused)</param>
        /// <param name="scopes">Scopes to request</param>
        /// <returns>An access token</returns>
        public override async Task <string> GetAccessTokenAsync(Uri resource, string[] scopes)
        {
            if (resource == null)
            {
                throw new ArgumentNullException(nameof(resource));
            }

            if (scopes == null)
            {
                throw new ArgumentNullException(nameof(scopes));
            }

            AuthenticationResult tokenResult = null;

            try
            {
                // Try to get the token from the tokens cache
                tokenResult = await confidentialClientApplication.AcquireTokenForClient(scopes).ExecuteAsync().ConfigureAwait(false);
            }
            catch (MsalServiceException)
            {
                // Handle the various exceptions
                throw;
            }

            // Log the access token retrieval action
            Log?.LogInformation(PnPCoreAuthResources.AuthenticationProvider_LogAccessTokenRetrieval,
                                GetType().Name, resource, scopes.Aggregate(string.Empty, (c, n) => c + ", " + n).TrimEnd(','));

            // Return the Access Token, if we've got it
            // In case of any exception while retrieving the access token,
            // MSAL will throw an exception that we simply bubble up
            return(tokenResult.AccessToken);
        }
        public async Task <string> GetToken()
        {
            if (_accessToken != null)
            {
                return(_accessToken);
            }

            var clientId     = _dataCollectionApiAuthenticationOptions.ClientId;
            var clientSecret = _dataCollectionApiAuthenticationOptions.ClientSecret;
            var scope        = _dataCollectionApiAuthenticationOptions.Scope;

            IConfidentialClientApplication app = ConfidentialClientApplicationBuilder.Create(clientId)
                                                 .WithClientSecret(clientSecret)
                                                 .WithAuthority(new Uri(_dataCollectionApiAuthenticationOptions.Authority))
                                                 .Build();

            string[] scopes = new string[] { scope };

            AuthenticationResult result;

            try
            {
                result = await app.AcquireTokenForClient(scopes).ExecuteAsync();
            }
            catch (MsalServiceException ex) when(ex.Message.Contains("AADSTS70011"))
            {
                throw new Exception("Invalid scope specified", ex);
            }

            _accessToken = result?.AccessToken;
            return(_accessToken);
        }
Beispiel #24
0
        public async Task <string> GetAccessToken()
        {
            string[] scopes = new string[] { "https://graph.microsoft.com/.default" };

            AuthenticationResult result = null;

            try
            {
                result = await app.AcquireTokenForClient(scopes)
                         .ExecuteAsync();
            }
            catch (MsalUiRequiredException ex)
            {
                // The application doesn't have sufficient permissions.
                // - Did you declare enough app permissions during app creation?
                // - Did the tenant admin grant permissions to the application?
                Console.WriteLine(ex.Message);
            }
            catch (MsalServiceException ex) when(ex.Message.Contains("AADSTS70011"))
            {
                // Invalid scope. The scope has to be in the form "https://resourceurl/.default"
                // Mitigation: Change the scope to be as expected.
            }

            return(result.AccessToken);
        }
        private void button8_Click(object sender, EventArgs e)
        {
            try
            {
                //Obtain token using client credentials.
                string[] scopescc = new string[] { "https://graph.windows.net/.default" };
                url = String.Format("https://login.microsoftonline.com/{0}/oauth2/v2.0/token", Domain.Text);

                IConfidentialClientApplication appcc = ConfidentialClientApplicationBuilder.Create(ClientID.Text).WithClientSecret(Secret.Text).WithRedirectUri(redirectURI.Text).Build();

                Task <Microsoft.Identity.Client.AuthenticationResult> ccToken = appcc.AcquireTokenForClient(scopescc).WithAuthority(url, true).ExecuteAsync();
                ccToken.Wait();

                ccAccessToken.Text = ccToken.Result.AccessToken;
            }
            catch (Microsoft.Identity.Client.MsalClientException eexc)
            {
                Logger.WriteLog("Issue encountered while generating access token using client credentials: " + eexc);
                throw;
            }
            catch (System.AggregateException eexc)
            {
                Logger.WriteLog("Issue encountered while generating access token using client credentials. Please make sure that you have input the correct data: " + eexc);
                throw;
            }
        }
Beispiel #26
0
        private async Task <AccessToken> GetTokenInteractiveAsync(string[] scopes, CancellationToken cancellationToken)
        {
            var authResult = await _publicClientApp.AcquireTokenForClient(scopes)
                             .ExecuteAsync(cancellationToken);

            return(new AccessToken(authResult.AccessToken, authResult.ExpiresOn));
        }
Beispiel #27
0
        private async Task <AuthenticationResult> GenerateBearerToken()
        {
            BuildContext();
            AuthenticationResult result;

            try
            {
                result = await Context.AcquireTokenForClient(scopes).ExecuteAsync();
            }
            catch (Exception ex)
            {
                var errorMsg = $"Exception: {ex.Message}";
                if (ex.InnerException != null)
                {
                    errorMsg += $" InnerException: {ex.InnerException.Message}";
                }
                throw new Exception($"There was an error while acquiring Syms Adapter's Token with client ID/secret authentication. {errorMsg}");
            }

            if (result == null || result.CreateAuthorizationHeader() == null)
            {
                throw new Exception("Received invalid Syms Adapter's authentication result. The result might be null, or missing HTTP authorization header from the authentication result.");
            }
            return(result);
        }
Beispiel #28
0
        private async Task <string> GetAccessToken()
        {
            // If there is no saved user account, the user must sign-in
            if (_userAccount == null)
            {
                try
                {
                    // Invoke device code flow so user can sign-in with a browser
                    var result = await _msalClient.AcquireTokenForClient(_scope).ExecuteAsync();

                    _userAccount = result.Account;
                    return(result.AccessToken);
                }
                catch (Exception exception)
                {
                    Console.WriteLine($"Error getting access token: {exception.Message}");
                    return(null);
                }
            }
            else
            {
                // If there is an account, call AcquireTokenSilent
                // By doing this, MSAL will refresh the token automatically if
                // it is expired. Otherwise it returns the cached token.
                var result = await _msalClient
                             .AcquireTokenSilent(_scope, _userAccount)
                             .ExecuteAsync();

                return(result.AccessToken);
            }
        }
Beispiel #29
0
        public async Task <ActionResult> GetMe()
        {
            IConfidentialClientApplication app = ConfidentialClientApplicationBuilder.Create(AuthenticationConfig.ClientId)
                                                 .WithAuthority(new Uri(AuthenticationConfig.Authority))
                                                 .WithClientSecret(AuthenticationConfig.ClientSecret)
                                                 .Build();

            AuthenticationResult result = null;
            var account = await app.GetAccountAsync(ClaimsPrincipal.Current.GetMsalAccountId());

            try
            {
                // try to get token silently
                //result = await app.AcquireTokenSilent(scopes, account).ExecuteAsync().ConfigureAwait(false);
                result = await app.AcquireTokenForClient(AuthenticationConfig.Scopes).ExecuteAsync().ConfigureAwait(false);
            }
            catch (MsalUiRequiredException)
            {
                ViewBag.Relogin = "******";
                return(View());
            }
            catch (Exception eee)
            {
                ViewBag.Error = "An error has occurred. Details: " + eee.Message;
                return(View());
            }

            if (result != null)
            {
                // Use the token to read email
                //HttpClient hc = new HttpClient();
                //hc.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", result.AccessToken);
                //HttpResponseMessage hrm = await hc.GetAsync("https://graph.microsoft.com/v1.0/me");

                //string rez = await hrm.Content.ReadAsStringAsync();
                //ViewBag.Message = rez;

                var accessToken = result.AccessToken;
                var graphClient = new GraphServiceClient(new DelegateAuthenticationProvider(async(requestMessage) =>
                {
                                        // Retrieve an access token for Microsoft Graph (gets a fresh token if needed).
                                        //var authResult = await app.AcquireTokenForClient(scopes).ExecuteAsync().ConfigureAwait(false);
                                        // Add the access token in the Authorization header of the API request.requestMessage.Headers.Authorization =
                                        requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
                }));
                //var eml = System.Web.HttpContext.Current.User.Identity.Name;
                var    eml = ClaimsPrincipal.Current.FindFirst("preferred_username");
                string upn = eml.Value;


                var user = await graphClient.Users[upn].Request()
                           //.Filter(eml)
                           .Select("id, department, displayName, employeeId, givenName, surname, jobTitle, userPrincipalName, officeLocation, onPremisesExtensionAttributes, userType")
                           .GetAsync();

                ViewBag.Message = user.UserPrincipalName;
            }

            return(View());
        }
Beispiel #30
0
        static async Task Main(string[] args)
        {
            confidentialClient = ConfidentialClientApplicationBuilder
                                 .Create(clientId)
                                 .WithAuthority(authority)
                                 .WithClientSecret(clientSecret)
                                 .Build();

            var scopes = new string[] { "https://graph.microsoft.com/.default" };

            AuthenticationResult result = await confidentialClient.AcquireTokenForClient(scopes).ExecuteAsync();

            Console.WriteLine(result.AccessToken);

            var httpClient  = new HttpClient();
            var httpRequest = new HttpRequestMessage(HttpMethod.Get,
                                                     "https://graph.microsoft.com/v1.0/sites/piasysdev.sharepoint.com:root/");

            httpRequest.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(
                "Bearer", result.AccessToken);

            var response = await httpClient.SendAsync(httpRequest);

            if (response.IsSuccessStatusCode)
            {
                Console.WriteLine(await response.Content.ReadAsStringAsync());
            }
            else
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(await response.Content.ReadAsStringAsync());
            }
        }