public async Task Get(string tenantId)
        {
            // Get a token for the Microsoft Graph
            ConfidentialClientApplication daemonClient = new ConfidentialClientApplication(String.Format(authorityFormat, tenantId), Startup.clientId, Startup.redirectUri, new ClientCredential(Startup.clientSecret), new TokenCache());
            AuthenticationResult          authResult   = await daemonClient.AcquireTokenForClient(new string[] { msGraphScope }, null);

            // Query for list of users in the tenant
            HttpClient         client  = new HttpClient();
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, msGraphQuery);

            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authResult.Token);
            HttpResponseMessage response = await client.SendAsync(request);

            if (!response.IsSuccessStatusCode)
            {
                throw new HttpResponseException(response.StatusCode);
            }

            // Record users in the data store (note that this only records the first page of users)
            string json = await response.Content.ReadAsStringAsync();

            MsGraphUserListResponse users = JsonConvert.DeserializeObject <MsGraphUserListResponse>(json);

            usersByTenant[tenantId] = users.value;
            return;
        }
        public async Task GetAsync()
        {
            string tenantId = "3485b963-82ba-4a6f-810f-b5cc226ff898";
            // Get a token for the Microsoft Graph. If this line throws an exception for any reason, we'll just let the exception be returned as a 500 response
            // to the caller, and show a generic error message to the user.

            IConfidentialClientApplication daemonClient;

            daemonClient = ConfidentialClientApplicationBuilder.Create(Startup.clientId)
                           .WithAuthority(string.Format(AuthorityFormat, tenantId))
                           .WithRedirectUri(Startup.redirectUri)
                           .WithClientSecret(Startup.clientSecret)
                           .Build();

            var serializedAppTokenCache  = new MSALAppTokenMemoryCache(daemonClient.AppTokenCache);
            var serializedUserTokenCache = new MSALUserTokenMemoryCache(daemonClient.UserTokenCache);

            AuthenticationResult authResult = await daemonClient.AcquireTokenForClient(new[] { MSGraphScope })
                                              .ExecuteAsync();

            // Query for list of users in the tenant
            HttpClient         client  = new HttpClient();
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, MSGraphQuery);

            request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
            //request.Content = new StringContent("{\"fields\": {\"Title\": \"asd\",\"Email\": \"[email protected]\"}\"}");
            HttpResponseMessage response = await client.SendAsync(request);

            var a = "2";

            // If the token we used was insufficient to make the query, drop the token from the cache. The Users page of the website will show a message to the user instructing them to grant
            // permissions to the app (see User/Index.cshtml).
            if (response.StatusCode == System.Net.HttpStatusCode.Forbidden)
            {
                // Here, we should clear MSAL's app token cache to ensure that on a subsequent call to SyncController, MSAL does not return the same access token that resulted in this 403.
                // By clearing the cache, MSAL will be forced to retrieve a new access token from AAD, which will contain the most up-to-date set of permissions granted to the app. Since MSAL
                // currently does not provide a way to clear the app token cache, we have commented this line out. Thankfully, since this app uses the default in-memory app token cache, the app still
                // works correctly, since the in-memory cache is not persistent across calls to SyncController anyway. If you build a persistent app token cache for MSAL, you should make sure to clear
                // it at this point in the code.
                serializedAppTokenCache.Clear(Startup.clientId);
            }

            if (!response.IsSuccessStatusCode)
            {
                throw new HttpResponseException(response.StatusCode);
            }

            // Record users in the data store (note that this only records the first page of users)
            string json = await response.Content.ReadAsStringAsync();

            JObject obj = await response.Content.ReadAsAsync <JObject>();

            MsGraphUserListResponse users = JsonConvert.DeserializeObject <MsGraphUserListResponse>(json);
            var b = users.value;

            usersByTenant[tenantId] = users.value;
        }
        public async Task Get(string tenantId)
        {
            // Get a token for the Microsoft Graph. If this line throws an exception for
            // any reason, we'll just let the exception be returned as a 500 response
            // to the caller, and show a generic error message to the user.
            ConfidentialClientApplication daemonClient = new ConfidentialClientApplication(
                Startup.clientId,
                String.Format(authorityFormat, tenantId),
                Startup.redirectUri,
                new ClientCredential(Startup.clientSecret),
                null,
                new TokenCache());
            AuthenticationResult authResult = await daemonClient.AcquireTokenForClientAsync(
                new string[] { msGraphScope });

            // Query for list of users in the tenant
            HttpClient         client  = new HttpClient();
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, msGraphQuery);

            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
            HttpResponseMessage response = await client.SendAsync(request);

            // If the token we used was insufficient to make the query, drop the token from the cache.
            // The Users page of the website will show a message to the user instructing them to grant
            // permissions to the app (see User/Index.cshtml).
            if (response.StatusCode == System.Net.HttpStatusCode.Forbidden)
            {
                // BUG: Here, we should clear MSAL's app token cache to ensure that on a subsequent call
                // to SyncController, MSAL does not return the same access token that resulted in this 403.
                // By clearing the cache, MSAL will be forced to retrieve a new access token from AAD,
                // which will contain the most up-to-date set of permissions granted to the app. Since MSAL
                // currently does not provide a way to clear the app token cache, we have commented this line
                // out. Thankfully, since this app uses the default in-memory app token cache, the app still
                // works correctly, since the in-memory cache is not persistent across calls to SyncController
                // anyway. If you build a persistent app token cache for MSAL, you should make sure to clear
                // it at this point in the code.
                //
                //daemonClient.AppTokenCache.Clear(Startup.clientId);
            }

            if (!response.IsSuccessStatusCode)
            {
                throw new HttpResponseException(response.StatusCode);
            }

            // Record users in the data store (note that this only records the first page of users)
            string json = await response.Content.ReadAsStringAsync();

            MsGraphUserListResponse users = JsonConvert.DeserializeObject <MsGraphUserListResponse>(json);

            usersByTenant[tenantId] = users.value;
            return;
        }
Beispiel #4
0
        static void Main(string[] args)
        {
            string ClientId     = System.Configuration.ConfigurationManager.AppSettings["ida:ClientId"];
            string TenantId     = System.Configuration.ConfigurationManager.AppSettings["ida:TenantId"];
            string ClientSecret = System.Configuration.ConfigurationManager.AppSettings["ida:ClientSecret"];
            string AadInstance  = System.Configuration.ConfigurationManager.AppSettings["ida:AadInstance"];
            string Scope        = System.Configuration.ConfigurationManager.AppSettings["ida:Scope"];

            string MSGraphQuery = "https://graph.microsoft.com/v1.0/users"; // Simulate downstream API call
            string oAuthUrl     = string.Format("{0}/{1}/oauth2/v2.0/token", AadInstance, TenantId);

            ////////////////////////////////// Get Bearer Token ////////////////////////////////////////////////////
            HttpClient         authClient  = new HttpClient();
            HttpRequestMessage authRequest = new HttpRequestMessage(HttpMethod.Post, oAuthUrl);

            var requestContent = string.Format("client_id={0}&scope={1}&client_secret={2}&grant_type=client_credentials", ClientId, Scope, ClientSecret);

            authRequest.Content = new StringContent(requestContent, Encoding.UTF8, "application/x-www-form-urlencoded");

            HttpResponseMessage authResponse = authClient.SendAsync(authRequest).Result;

            var authJson = JsonConvert.DeserializeObject <AuthToken>(authResponse.Content.ReadAsStringAsync().Result);

            Console.WriteLine("Bearer Token : " + authJson.access_token);
            ///////////////////////////////////////////////////////////////////////////////////////////////////////


            //////////////////////// Call Downstream API - In this case MS Graph API //////////////////////////////
            HttpClient         gClient = new HttpClient();
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, MSGraphQuery);

            request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authJson.access_token);
            HttpResponseMessage response = gClient.SendAsync(request).Result;

            string json = response.Content.ReadAsStringAsync().Result;
            MsGraphUserListResponse users = JsonConvert.DeserializeObject <MsGraphUserListResponse>(json);

            Console.WriteLine("--------");

            Console.WriteLine(users.value.First().userPrincipalName);
            ///////////////////////////////////////////////////////////////////////////////////////////////////////

            Console.ReadLine();
        }