Jeff Saremi Jeff Saremi - 3 months ago 128
C# Question

How can I force the AdminConsent using AuthenticationContext.AcquireTokenAsync?

I have a native app which i'm using in a multi-tenant scenario.
To authenticate the user -- and to get their consent on allowing this application to access Azure on their behalf -- I simply instantiate an AuthenticationContext and call AcquireTokenAsync. However I don't know how if this by default uses the AdminConsent or not? If not how can i achieve that?

Below is the sample code that i use:

AuthenticationContext commonAuthContext = new AuthenticationContext("https://login.microsoftonline.com/common");
AuthenticationResult result = await commonAuthContext.AcquireTokenAsync(resource,
clientId, replyUrl,
new PlatformParameters(PromptBehavior.Always));

Answer

No, this does not automatically invoke admin consent (even if an admin consents, they're just consenting for themselves, not for the whole tenant).

To invoke admin consent, you have to add prompt=admin_consent to the authentication request:

AuthenticationResult result = await commonAuthContext.AcquireTokenAsync(
    resource,
    clientId,
    replyUrl,
    new PlatformParameters(PromptBehavior.Auto), // <-- Important: use PromptBehavior.Auto
    UserIdentifier.AnyUser,
    "prompt=admin_consent"); // <-- This is the magic

Of course, you should not send all users to sign in with this, as it will fail if the user is not an admin.

See "Triggering the Azure AD consent framework at runtime": https://azure.microsoft.com/en-us/documentation/articles/active-directory-integrating-applications/#triggering-the-azure-ad-consent-framework-at-runtime