如何在最新的Microsoft.IdentityModel.Clients.ActiveDirectory中使用PromptBehavior AcquireToken

时间:2016-06-24 11:55:39

标签: azure azure-active-directory azure-automation

在旧版本的Microsoft.IdentityModel.Clients.ActiveDirectory中,存在带有PromptBehavior参数的AcquireToken

var context = new AuthenticationContext("https://login.windows.net/tenantId");
var result = context.AcquireToken(clientId: clientIdValue, redirectUri: new Uri("http://localhost/Appcycle"), resource: "https://management.core.windows.net/", promptBehavior: PromptBehavior.Auto);

在Microsoft.IdentityModel.Clients.ActiveDirectory v3.10中,只有AcquireTokenAsync

var authParam = new PlatformParameters(PromptBehavior.Auto,false);
var result = context.AcquireTokenAsync("https://management.core.windows.net/", clientid, new Uri("http://localhost/AppPoolRecycle"), authParam);
result.Wait();

当我运行时,我得到错误 {"无效的所有者窗口类型。预期的类型是IWin32Window或IntPtr(用于窗口句柄)。"}

不确定这是否是由于我在控制台应用程序上运行。如果是这样,我如何让它工作?

1 个答案:

答案 0 :(得分:6)

您收到此错误的原因是因为您传入" false"对于PlatformParameters构造函数中的第二个参数。

在最新版本的ADAL(Microsoft.IdentityModel.Clients.ActiveDirectory v3.10)中,第二个参数是(来自https://github.com/AzureAD/azure-activedirectory-library-for-dotnet/blob/7c9091a0edecf401fea402275e4a64aca95e40fe/src/ADAL.PCL.Desktop/PlatformParameters.cs):

    /// <summary>
    /// Gets the owner of the browser dialog which pops up for receiving user credentials. It can be null.
    /// </summary>
    public object OwnerWindow { get; private set; }

你传递的是false,在编译时被接受,因为它是一个对象,但是在运行时没有,因为它不是一个窗口。

要解决此问题,请不要传递此参数或将其作为null传递。这将使您的控制台应用程序启动一个窗口,提示用户登录。

如果这是一个应该运行但没有任何用户交互的控制台应用程序,那么你应该通过AcquireTokenAsync的另一个重载来使用仅限应用程序的流程:

    /// <summary>
    /// Acquires security token from the authority.
    /// </summary>
    /// <param name="resource">Identifier of the target resource that is the recipient of the requested token.</param>
    /// <param name="clientCredential">The client credential to use for token acquisition.</param>
    /// <returns>It contains Access Token and the Access Token's expiration time. Refresh Token property will be null for this overload.</returns>        
    public async Task<AuthenticationResult> AcquireTokenAsync(string resource, ClientCredential clientCredential)