a b a b - 11 months ago 98
reST (reStructuredText) Question

403 error received when trying to OAUTH authenticate WebClient against Microsoft Azure Graph

I am trying to write a simple console app which will authenticate using OAUTH against Azure Graph without the need for username/password, but I'm receiving a 403 error when executing the WebClient.DownloadString method. Any help would be greatly appreciated.

static void Main(string[] args)
{
// Constants
var tenant = "mytenant.onmicrosoft.com";
var resource = "https://graph.microsoft.com/";
var clientID = "blah-blah-blah-blah-blah";
var secret = "blahblahblahblahblahblah";

// Ceremony
var authority = $"https://login.microsoftonline.com/{tenant}";
var authContext = new AuthenticationContext(authority);
var credentials = new ClientCredential(clientID, secret);


// Obtain Token
var authResult = authContext.AcquireToken(resource, credentials);

WebClient webClient1 = new WebClient();
webClient1.Headers[HttpRequestHeader.Authorization] = "Bearer " + authResult.AccessToken;

webClient1.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
webClient1.Headers[HttpRequestHeader.Accept] = "application/json";

string payload = webClient1.DownloadString("https://graph.microsoft.com/v1.0/users?$Select=givenName,surname");

}
}

a b a b
Answer Source

This has now been resolved. The code above was correct, but there was a step I was missing, which is to configure the ServicePrincipal in Azure:-

  1. Login with a Global Admin using the command Connect-Msolservice
  2. Retrieve the ObjectID of the Service Principal > Get-MsolServicePrincipal –AppPrincipalId YOUR_APP_CLIENT_ID
  3. Assign the role using > Add-MsolRoleMember -RoleMemberType ServicePrincipal -RoleName ‘Company Administrator’ -RoleMemberObjectId YOUR_OBJECT_ID

The following links were also very useful:-

https://developer.microsoft.com/en-us/graph/docs/concepts/overview (Click the arrow in the top left to show the full list and then scroll down to the appropriate operation)

https://msdn.microsoft.com/en-us/library/azure/ad/graph/howto/azure-ad-graph-api-error-codes-and-error-handling

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download