lbpoundz
lbpoundz

Reputation: 71

can't generate a token to authenticate a service principal against Entra ID

I'm following the below documentation to authenticate against Microsoft Translator service with Microsoft Entra ID (Azure AD)

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

i'm stuck on the step to generate a token

important: key-based authentication is disabled on my translator instance therefore i've followed the docs above to another link to get token:

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

this seems to be abit outdated as it's using Powershell ADAL module to request a token, however i ran it anyways:

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

i filled in details with my serviceprincipal which has the roles assigned, yet i get no errors and $token returns empty

can anyone points me in the right direction please?

Upvotes: 0

Views: 464

Answers (1)

Sridevi
Sridevi

Reputation: 22307

I have one service principal with Cognitive Services User role under Translator resource like this:

enter image description here

To generate the access token, make use of below updated PowerShell script:

$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

Response:

enter image description here

Now, you can use this access token to call Microsoft Translator API successfully like this:

$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)"
}

Response:

enter image description here

Reference: Translator Languages Method - Azure AI services | Microsoft

Upvotes: 2

Related Questions