Last active
September 25, 2019 18:41
-
-
Save mhagrelius/716b2a021cb63148fa8a8c3162931770 to your computer and use it in GitHub Desktop.
Retrieve Groups From Microsoft Graph
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
/* | |
Uses Flurl.Http instead of default http client | |
Your app registration will need the appropriate permissions for microsoft graph | |
*** Additional exception handling needed if in a production scenario *** | |
*/ | |
public static class Program | |
{ | |
public async Task Main() | |
{ | |
var tenantId = "<insert tenant id>"; | |
var clientId = "<insert client id>"; | |
var oid = "<objectidentifier from claims>"; // this is the unique guid from microsoft | |
var clientSecret = "<insert client secret>"; | |
var graphUrl = $"https://graph.microsoft.com/v1.0/users/${oid}/memberOf"; | |
var result = await $"https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/token".PostUrlEncodedAsync(new | |
{ | |
client_id = clientId, | |
client_secret = clientSecret, | |
scope = "https://graph.microsoft.com/.default", | |
grant_type = "client_credentials" | |
}).ReceiveJson<TokenResponse>(); | |
if(!string.IsNullOrWhiteSpace(result.access_token)) | |
{ | |
var groupResponse = await $"https://graph.microsoft.com/v1.0/users/{oid}/memberOf".WithHeader("Authorization", $"Bearer {result.access_token}").GetJsonAsync<GroupsResponse>(); | |
// WORK WITH GROUPS FROM HERE | |
} | |
} | |
public class TokenResponse { | |
public string token_type; | |
public int expires_in; | |
public int ext_expires_in; | |
public string access_token; | |
} | |
public partial class GroupsResponse | |
{ | |
public Uri OdataContext { get; set; } | |
public List<Value> Value { get; set; } | |
} | |
public partial class Value | |
{ | |
public Guid Id { get; set; } | |
public string Description { get; set; } | |
public string DisplayName { get; set; } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment