Home > OS >  Invoke-RestMethod :unauthorized client for getting Authentication-token
Invoke-RestMethod :unauthorized client for getting Authentication-token

Time:11-19

I have created app registration in azure active directory. I'm trying to invoke an azure ad authenticated with below PowerShell script, but it always display an error:

$clientID = '<clientID>'
$secretKey = '<key>'
$tenantID = '<TenantID>'

$password = ConvertTo-SecureString -String $secretKey -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential($ClientID,$password)
Connect-AzureRmAccount -ServicePrincipal -Credential $credential -Tenant $tenantID

$authUrl = "https://login.microsoftonline.com/"   $tenantID   "/oauth2/v2.0/token/"
$body = @{
   "scope" = "api://a193b314b-7854-9aab-bb78-6a50ffxxxxxx/";
   "grant_type" = "client_credentials";
   "client_id" = $ClientID
   "client_secret" = $secretKey
}

Write-Output "Getting Authentication-Token" 
$adlsToken = Invoke-RestMethod -Uri $authUrl –Method POST -Body $body
Write-Output $adlsToken

I am getting this error. please make me to understand Why I am getting this error

Invoke-RestMethod: {"error":"invalid_scope","error_description":"AADSTS1002012: The provided value for scope api://3e3643c5-90af-ece is not valid. Client credential flows must have a scope value with /.default suffixed to the resource identifier (application ID URI).\r\nTrace ID:2d4f23bf-b317-4d5c-b5xxxxx\r\nCorrelation ID:fe5945b4-b2c2-4814-9xxxxxxx\r\nTimestamp:04:26:09Z","error_codes":[1002012],"timestamp":"2022-11-19 04:26:09Z","trace_id":"2d4f23bfb3174d5cb5a7xxxxxxx","correlation_id":"fe5945b4-b2c2-4814-99xxxxxxxx"}

Connect-AzAccount: ClientSecretCredential authentication failed: AADSTS700016: Application with identifier '3e3643c5-90af-4af6-afxxxxxxx' was not found in the directory 'Default

CodePudding user response:

I tried to reproduce the same in my environment I got the same error as below:

enter image description here

To resolve this issue, check whether you are providing correct ClientID as below:

enter image description here

And, In scope the error mention you have missed /.default Make sure to include /.default like below:

"api://xxxxxx/.default";

When I ran the same script along with scope default, I got the Result successfully like below:

enter image description here

CodePudding user response:

Can you try this by adding .default in scope,

"scope" = "api://a193b314b-7854-9aab-bb78-6a50ffxxxxxx/.default"

If it works, see the reference.

  • Related