Tuesday, February 7, 2017

How to consent to an Office 365 service app

At times you might want to create services which interact with the Microsoft Graph or Office 365 API’s.

If your application has an actual web page you will get prompted for consent when you visit and login. If you have elevated privileges you would tack on &prompt=admin_consent to the URL and then your service can authenticate and do what you need it to.



If you create an Office 365 application entry in Azure AD and have no web application tied to it, this is not automatic.

One approach to get the consent URL is to create a small c# app using the ADAL libraries.

string ResourceId = "https://graph.microsoft.com"; // Microsoft Graph End-point
Uri RedirectUri = new Uri("[APP ID URI]");
ClientId = "[O365 App ClientId]";
ClientSecret = "[O365 App ClientSecret]";

var authenticationContext = new AuthenticationContext("https://login.windows.net/common/");
var url = await authenticationContext.GetAuthorizationRequestUrlAsync(ResourceId, ClientId, RedirectUri, UserIdentifier.AnyUser, "prompt=admin_consent");
Console.WriteLine(url);

If you have a multi-tenant app, you have to login to each tenant using the outputted URL to consent per tenant.