authentication - 试图从证书中获取访问令牌
问题描述
我已经使用我的 Web API 应用程序配置了 Azure AD。添加了客户端 ID、证书、租户 ID 所需的配置。身份验证上下文失败:我使用 ADAl v5.2.9,authcontext 没有读取诸如 resourceid、clientcredentials 之类的值
Add-Type -Path "..\ADAL\Microsoft.IdentityModel.Clients.ActiveDirectory.dll"
# Output Token and Response from AAD Graph API
$accessToken = ".\Token.txt"
$output = ".\Output.json"
# Application and Tenant Configuration
$clientId = "<AppIDGUID>"
$tenantId = "<TenantID>"
$resourceId = "https://graph.windows.net" <using my own API>
$login = "https://login.microsoftonline.com"
# Create Client Credential Using Certificate
$certFile = "<PFXFilePath>"
$certFilePassword = "<CertPassword>"
$secret = New-Object -TypeName System.Security.Cryptography.X509Certificates.X509Certificate -ArgumentList $certFile,$certFilePassword
# Get an Access Token with ADAL
$clientCredential = New-Object Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential($clientId,$secret)
$authContext = New-Object Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext("{0}/{1}" -f $login,$tenantId)
$authenticationResult = $authContext.AcquireToken($resourceId, $clientcredential)
($token = $authenticationResult.AccessToken) | Out-File $accessToken
# Call the AAD Graph API
$headers = @{
"Authorization" = ("Bearer {0}" -f $token);
"Content-Type" = "application/json";
}
# Output response into a JSON file
Invoke-RestMethod -Method Get -Uri ("{0}/{1}/users?api-version=1.6" -f $resourceId,$tenantId) -Headers $headers -OutFile $output
低于错误
MethodInvocationException: C:\Users\final.ps1:22
Line |
22 | $authenticationResult = $authContext.AcquireToken($resourceId,$client …
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| Exception calling "AcquireToken" with "2" argument(s): "sts_token_request_failed: Token request to security token
| service failed. Check InnerException for more details"
解决方案
请尝试修改:
$authenticationResult = $authContext.AcquireToken($resourceId, $clientcredential)
($token = $authenticationResult.AccessToken) | Out-File $accessToken
至:
$authenticationTask = $authContext.AcquireTokenAsync($resourceId, $clientcredential)
$authenticationTask.Wait()
$authenticationResult = $authenticationTask.Result
($token = $authenticationResult.AccessToken) | Out-File $accessToken
推荐阅读
- javascript - 如何迭代模式的属性类型
- python - 有什么方法可以限制 Selenium 查找元素的时间吗?
- python - Python:传递记录器是个好主意吗?
- python - 如何制作 django 临时列表?
- oracle - 在一个过程中调用多个过程
- c# - 如何根据参数将数据插入到两个表中
- javascript - 是否可以检测何时在 JavaScript 中创建 ES6 类的第一个实例?
- selenium - 硒按钮单击python
- python - 如何使用 Python 发出 URL 请求并返回重定向到的 URL?
- prolog - 如何在 ECLIPSE-CLP 或 Prolog 中实现这些 Sigma 符号