Last active
February 8, 2019 20:18
-
-
Save vman/b44f77e5f31eb0aa82b0bd86c7e7e513 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Microsoft.IdentityModel.Clients.ActiveDirectory; | |
using System; | |
using System.Globalization; | |
using System.Net.Http; | |
using System.Net.Http.Headers; | |
namespace AppPermissionsDemo | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
string clientId = "<client-id-of-aad-app-registration>"; //e.g. 01e54f9a-81bc-4dee-b15d-e661ae13f382 | |
string clientSecret = "<client-secret-of-aad-app-registration>"; //e.g @FgQR{Q4I0.+^4v+/k{!.]&I/+j | |
string tenantDomain = "yourtenant.onmicrosoft.com"; | |
string accessToken = GetMSGraphApplicationAccessToken(clientId, clientSecret, tenantDomain); | |
HttpClient httpClient = new HttpClient(); | |
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); | |
//Sample request to get all groups. The AAD App registration will need at least Group.Read.All application permission granted. | |
var request = new HttpRequestMessage(HttpMethod.Get, $"https://graph.microsoft.com/v1.0/groups"); | |
var response = httpClient.SendAsync(request).Result; | |
var content = response.Content.ReadAsStringAsync().Result; | |
Console.WriteLine(content); | |
} | |
public static string GetMSGraphApplicationAccessToken(string clientId, string clientSecret, string tenantDomain) | |
{ | |
string authority = string.Format(CultureInfo.InvariantCulture, "{0}/{1}/", "https://login.windows.net", tenantDomain); | |
var authContext = new AuthenticationContext(authority); | |
var clientCredential = new ClientCredential(clientId, clientSecret); | |
var result = authContext.AcquireTokenAsync("https://graph.microsoft.com", clientCredential).Result; | |
var accessToken = result.AccessToken; | |
return accessToken; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment