Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
612 views
in Technique[技术] by (71.8m points)

powershell - Getting 401 while trying perform API call with bearer token which is deployed and protected with Azure Ad Authentication

Im trying to create a runbook using powershell, while calling the api(Deployed in azure) using invoke webrequest,im passing the access token in headers and im not getting authenticated.

$TenantId="xyxyxyx"
$MapUrl="https://graph.microsoft.com"
$Authority="https://login.microsoftonline.com/$TenantId"
$ClientSecret="secret"
$AuthContext=New-Object "Micorsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext -argumentlist $Authority
$ClientCredential=New-Object "Micorsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential -argumentlsit $ClientId,$ClientSecret
$ResultToken=$AuthContext.AcquireTokenAsync($MapUrl,$ClientCredential).Result


By Using the above steps i got the access token then im using the token in the request like this

Invoke-WebRequest -uri 'https://sssss/api/Get' -Headers @{"Authorization"="(Bearer $ResultToken.AccessToken)"}


I dont know what im missing can someone help me with this. Thanks in Advance

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your script obtains the access token for Microsoft Graph API, to call your custom API, you need to obtain the access token for the AD App which represents your API.

Navigate to the portal -> Azure Active Directory -> App registrations -> find the AD App which represents your API -> Expose an API -> get the Application ID URI(if you didn't set it, click Set to set it).

enter image description here

Then in your script, change the $MapUrl with it.

$MapUrl="Application ID URI"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...