无法生成令牌来根据 Entra ID 验证服务主体

问题描述 投票:0回答:1

我按照以下文档使用 Microsoft Entra ID (Azure AD) 对 Microsoft Translator 服务进行身份验证

https://learn.microsoft.com/en-us/azure/ai-services/translator/reference/v3-0-reference#authentication-with-microsoft-entra-id

我被困在生成令牌的步骤上

重要提示:我的翻译器实例上禁用了基于密钥的身份验证,因此我已按照上面的文档转到另一个链接来获取令牌:

https://learn.microsoft.com/en-us/azure/ai-services/authentication?tabs=powershell#sample-request

这似乎有点过时了,因为它使用 Powershell ADAL 模块来请求令牌,但我还是运行了它:

Install-Module -Name ADAL.PS
Import-Module -Name ADAL.PS
$authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" -ArgumentList "https://login.windows.net/<TENANT_ID>"
$secureSecretObject = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.SecureClientSecret" -ArgumentList $SecureStringPassword   
$clientCredential = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential" -ArgumentList $app.ApplicationId, $secureSecretObject
$token=$authContext.AcquireTokenAsync("https://cognitiveservices.azure.com/", $clientCredential).Result
$token

我用分配了角色的 serviceprincipal 填写了详细信息,但我没有收到任何错误,并且 $token 返回空

有人可以指出我正确的方向吗?

azure authentication microsoft-translator microsoft-entra-id
1个回答
0
投票

我有一个服务主体,在翻译器资源下具有认知服务用户角色,如下所示:

enter image description here

要生成访问令牌,请使用以下更新 PowerShell 脚本:

$tenantId = "tenantId"
$clientId = "appId"
$clientSecret = "secret"
$resourceUrl = "https://cognitiveservices.azure.com/"

$tokenEndpoint = "https://login.microsoftonline.com/$tenantId/oauth2/token"
$body = @{
    grant_type    = "client_credentials"
    client_id     = $clientId
    client_secret = $clientSecret
    resource      = $resourceUrl
}

$responseToken = Invoke-RestMethod -Uri $tokenEndpoint -Method Post -Body $body
$accessToken = $responseToken.access_token

回复:

enter image description here

现在,您可以使用此访问令牌成功调用 Microsoft Translator API,如下所示:

$translatorApiUrl = "https://api.cognitive.microsofttranslator.com/languages?api-version=3.0"

$headers = @{
    Authorization = "Bearer $accessToken"
    "Content-Type" = "application/json"
}

try {
    $response = Invoke-RestMethod -Uri $translatorApiUrl -Method Get -Headers $headers -ErrorAction Stop
    $response | ConvertTo-Json

}
catch {
    Write-Host "Error: $($_.Exception.Message)"
}

回复:

enter image description here

参考: 翻译语言方法 - Azure AI 服务 |微软

© www.soinside.com 2019 - 2024. All rights reserved.