azure - 如何在最新的 Microsoft.IdentityModel.Clients.ActiveDirectory 中使用 PromptBehavior 获取 token

标签 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(对于窗口句柄)。”}

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

最佳答案

出现此错误的原因是您在 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; }

您传入的是 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)

关于azure - 如何在最新的 Microsoft.IdentityModel.Clients.ActiveDirectory 中使用 PromptBehavior 获取 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38012875/

相关文章:

python - 使用 argparse 错误地传递参数

azure - 由于现有应用程序,无法删除 Azure Active-Directory

windows - 即使使用同一用户进行服务,也无法通过 Windows 服务访问 UNC 路径

创建 Azure SQL 数据库时的 Azure 自动化或 Azure Function

c# - ASP 的 Request.IsLocal 在 Azure 中始终为 true

azure - QnA Maker 在 MS Teams 中部署时不显示按钮

asp.net-web-api - 具有通配符名称的基于 asp.net 角色的授权

azure-active-directory - 使用 Azure Function 应用程序的登录用户验证 Dynamics 365 Web Api

azure - 在 azure 自动化上执行 Invoke-AzureRmVMRunCommand 时出现问题

Azure Runbook 启动/停止计划列表