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

kum*_*mar 5 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);
Run Code Online (Sandbox Code Playgroud)

在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();
Run Code Online (Sandbox Code Playgroud)

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

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

Sac*_*aca 6

出现此错误的原因是因为您要在PlatformParameters构造函数中为第二个参数传递“ false”。

在最新版本的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; }
Run Code Online (Sandbox Code Playgroud)

您传入的是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)
Run Code Online (Sandbox Code Playgroud)