Using GraphAPI From WebAPI

I will Polish this post later, meanwhile:

Go In Azure Register an APP

  • Get Client ID:
  • Generate Key
  • Permissions to other application: Read Directory Data ( Very important else nothing will work)

Packages Required:

https://www.nuget.org/packages/Microsoft.Azure.ActiveDirectory.GraphClient/2.0.5

https://www.nuget.org/packages/Microsoft.IdentityModel.Clients.ActiveDirectory/2.14.201151115

 

Web.config

<appSettings><add key=”ida:ClientID” value=”a69ce710-2edc-4cf2-bf40-ded19bb28e08″ />
<add key=”ida:AppKey” value=”KEY GENERATED FROM AZURE” />
<add key=”ida:GraphUrl” value=”https://graph.windows.net” />
<add key=”ida:authString” value=”https://login.windows.net/stephangaleagmail.onmicrosoft.com” />
<add key=”ida:graphURL” value=”https://graph.windows.net/stephangaleagmail.onmicrosoft.com” /></appSettings>

 

Getting an instance of ADClient

private static async Task<string> GetAppTokenAsync()
{
AuthenticationContext authenticationContext = new AuthenticationContext(ConfigurationManager.AppSettings[“ida:authString”], false);
ClientCredential clientCred = new ClientCredential(ConfigurationManager.AppSettings[“ida:ClientId”], ConfigurationManager.AppSettings[“ida:AppKey”]);
AuthenticationResult authenticationResult = await authenticationContext.AcquireTokenAsync(ConfigurationManager.AppSettings[“ida:GraphUrl”], clientCred);
return authenticationResult.AccessToken;
}

Uri serviceRoot = new Uri(ConfigurationManager.AppSettings[“ida:graphURL”]);
ActiveDirectoryClient adClient = new ActiveDirectoryClient(
serviceRoot,
async () => await GetAppTokenAsync());

 

Looking up a user
var upn = “test@stephangaleagmail.onmicrosoft.com”;
var userLookup = adClient.Users.Where(
user => user.UserPrincipalName.Equals(
upn, StringComparison.CurrentCultureIgnoreCase)).ExecuteSingleAsync();

User user1= (User)await userLookup;