如何使用 AuthenticationContext.AcquireTokenAsync 强制 AdminConsent?

How can I force the AdminConsent using AuthenticationContext.AcquireTokenAsync?

我有一个在多租户场景中使用的本机应用程序。 为了对用户进行身份验证——并征得他们同意允许此应用程序代表他们访问 Azure——我只需实例化一个 AuthenticationContext 并调用 AcquireTokenAsync。但是我不知道这是否默认使用 AdminConsent?如果不是,我该如何实现?

下面是我使用的示例代码:

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

不,这不会自动调用管理员同意(即使管理员同意,他们只是为自己同意,而不是为整个租户同意)。

要调用管理员许可,您必须将 prompt=admin_consent 添加到身份验证请求中:

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

当然,你不应该让所有用户都用这个登录,因为如果用户不是管理员,它将失败。

参见"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