首页 > 解决方案 > 试图从证书中获取访问令牌

问题描述

我已经使用我的 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"

标签: authenticationazure-active-directorypowershell-2.0adal

解决方案


请尝试修改:

$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

推荐阅读