Skip to content

Instantly share code, notes, and snippets.

@jackawatts
Last active January 25, 2019 04:08
Show Gist options
  • Save jackawatts/d9616d3334c49367f44e31b6958551d9 to your computer and use it in GitHub Desktop.
Save jackawatts/d9616d3334c49367f44e31b6958551d9 to your computer and use it in GitHub Desktop.
Working with Azure AD and Graph API

Access to the GraphAPI requires an auth token best collected via ADAL.NET MSAL.NET is an alternative but it does not handle caching elegantly

Configure Azure AD to have the correct permissions

  1. Login to portal.azure.com
  2. Azure AD
  3. Visit the app registration
  4. Settings => Required Permissions
  5. Add Graph API if it does not already appear in the list
  6. Add the appropriate permissions (as an app typically)
  7. Grant the permissions

Authenticating with the API

private async Task<GraphServiceClient> GetGraphServiceClient()
{
  var ctx = new AuthenticationContext(($"https://login.microsoftonline.com/{_domain}/"));
  var clientCredential = new ClientCredential(_clientId, _clientSecret);

  var token = await ctx.AcquireTokenAsync("https://graph.microsoft.com/", clientCredential);

  var graphServiceClient = new GraphServiceClient(new DelegateAuthenticationProvider((requestMessage) => {
      requestMessage
      .Headers
      .Authorization = new AuthenticationHeaderValue("bearer", token.AccessToken);

    return Task.CompletedTask;
  }));

  return graphServiceClient;
}

Viewing User properties in Azure Console

Get-AzureADUser -ObjectId $UserId | Select -ExpandProperty ExtensionProperty
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment