PowerShell- Use Credentials instead of Basic Bas64 with Token to Invoke-RestMethod against AzureDevops - azure

I have PowerShell scripts that I run to kick off a build in Azure DevOps as well as doing lots of things in Azure DevOps using the Rest API. I am currently using the token that is converted to Base64 using basic in the header to authenticate. If there a way of using -Credentials (Get-Credentials) with the token instead of a base64 header encoded token when using Invoke-RestMethod? Below is a sample for connecting with the Base64 token and Basic.
Sample script that lists Projects:
$token = "##############################################"
$UriOrg = "https://dev.azure.com/myADO/"
$AzureDevOpsAuthenicationHeader = #{Authorization = 'Basic ' + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(":$($token)")) }
$uriProcess = $UriOrg + "_apis/process/processes?api-version=5.1"
Invoke-RestMethod -Uri $uriProcess -Method get -Headers $AzureDevOpsAuthenicationHeader

Although Get-Credential is designed to get a credential using a username and password, you can of course also use it to have someone enter the token..
Something like
$cred = Get-Credential -Message 'Please enter the AzureDevops Token in the Password field' -UserName 'AzureDevops'
if ($cred) {
$token = $cred.GetNetworkCredential().Password
$authHeader = #{Authorization = 'Basic ' + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(":$($token)")) }
$UriOrg = 'https://dev.azure.com/myADO/'
$uriProcess = $UriOrg + "_apis/process/processes?api-version=5.1"
Invoke-RestMethod -Uri $uriProcess -Method Get -Headers $authHeader
}
Another option would be to create your own form where it is also possible to enter the Uri for the organization, because Get-Credential does not accept usernames like https://dev.azure.com/myADO/

Related

connecting to azure rest api using powershell resulting in StatusCode : 203 StatusDescription : Non-Authoritative Information

I am able to connect fine to azure API's using a PAT token in postman, however am not able to authenticate using powershell.
After playing around with different authorization passing I am still stuck with getting the html page for the sign in returned. Here is a sample request I am making
Invoke-RestMethod https://feeds.dev.azure.com/xx/x/_apis/packaging/Feeds/x/Packages -Headers #{Authorization="Token :xxx"}
After much searching I came across https://www.opentechguides.com/how-to/article/azure/201/devops-rest-powershell.html. Here is a simplified snippet that allowed my request to go through successfully.
#enter your token in pat token
$pat = "xxx"
# Create header with PAT
$token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($pat)"))
$header = #{authorization = "Basic $token"}
#enter your url in projects url
$projectsUrl = "https://feeds.dev.azure.com/xx/x/_apis/packaging/Feeds/x/Packages -Headers"
$projects = Invoke-RestMethod -Uri $projectsUrl -Method Get -ContentType "application/json" -Headers $header

Get-AzAccessToken keeps returning the same Token by targeting a different tenant

I have a PowerShell Azure Function that is secured with AAD. In my script I get the id token with the following command:
$assertion = $Request.Headers['x-ms-token-aad-id-token']
I use this assertion in order to get another token to use the Azure Service Management Api with the OBO Flow. Below is the code used:
$contentType = 'application/x-www-form-urlencoded'
$body = #{
grant_type = $grantType
client_id = $clientId
client_secret = $clientSecret
scope = $scope
requested_token_use = $requestedTokenUse
assertion = $assertion
}
$oboResponse = Invoke-RestMethod 'https://login.microsoftonline.com/e005f490-xxxx-4816-xxxx-b0ed7fa9xxxx/oauth2/v2.0/token' -Method 'POST' -body $body -ContentType $contentType
$accessToken = $oboResponse.access_token
Then I use this token to connect to azure with the Connect-AzAccount command. So far, everything is good well and the connection to Azure is working fine.
In my script, I try to have different tokens to connect to other tenants to which I belong. Unfortunately, it does not work as expected. Indeed the command returns the same token for different tenants. In fact, the produced token by the command "Get-AzAccessToken -TenantId $tenant.Id" is always equal to the token produced by the OBO flow.
Below is my PowerShell Azure function. I commented the part where I have a the issue.
using namespace System.Net
# Input bindings are passed in via param block.
param($Request, $TriggerMetadata)
$accountId = $Request.Headers['x-ms-client-principal-name']
$grantType = "urn:ietf:params:oauth:grant-type:jwt-bearer"
$clientId = "xxxx"
$clientSecret = "xxxx"
$scope = "https://management.azure.com/user_impersonation"
$requestedTokenUse = "on_behalf_of"
$assertion = $Request.Headers['x-ms-token-aad-id-token']
$contentType = 'application/x-www-form-urlencoded'
$body = #{
grant_type = $grantType
client_id = $clientId
client_secret = $clientSecret
scope = $scope
requested_token_use = $requestedTokenUse
assertion = $assertion
}
$oboResponse = Invoke-RestMethod 'https://login.microsoftonline.com/e005f490-xxxx-4816-xxxx-b0ed7fa9xxxx/oauth2/v2.0/token' -Method 'POST' -body $body -ContentType $contentType
$accessToken = $oboResponse.access_token
Connect-AzAccount -AccessToken $accessToken -AccountId $accountId
$allTenants = Get-AzTenant
foreach ($tenant in $allTenants) {
# Here I get the same access token for different tenants.
# The token is always equal to the token produced by the OBO flow.
$accessToken_ = Get-AzAccessToken -TenantId $tenant.Id
....
....
}
...
...
I don't understand why the token produced by the OBO flow is always equal to the token produced by Get-AzAccessToken. I hope I have described my problem correctly, thank you for your help.
Thank you.
I think the problem is due to your Invoke-RestMethod call using a static tenant ID/GUID:
$oboResponse = Invoke-RestMethod 'https://login.microsoftonline.com/e005f490-xxxx-4816-xxxx-b0ed7fa9xxxx/oauth2/v2.0/token' -Method 'POST' -body $body -ContentType $contentType
https://login.microsoftonline.com/{**tenant**}/oauth2/v2.0/token

my Azure ML api rest return an empty object

My issue
I try using REST API for machine learning. The following PowerShell doesn't fail, but return an empty objet, whatever the API I am testing.
my SPN has contributor permission, I made grant consent and I checked I get a token.
the doc I was using:
https://learn.microsoft.com/fr-fr/rest/api/azureml/quotas/list
I tested several other GET API as well.
I don't know what to do more. Any idea?
My Powershell code
$tenant_id = "XXXXXXXXXXXXXXXXXXX"
$ApplicationId = "XXXXXXXXXXXXXXX"
$spn_client_secret = "XXXXXXXXXXXXX"
$subscriptionid="XXXXXXXXXXXX"
$uri = "https://login.microsoftonline.com/$tenant_id/oauth2/token"
$BodyText = "grant_type=client_credentials&client_id=$ApplicationId&resource=https://management.azure.com&client_secret=$spn_client_secret"
# GET TOKEN
$Response = Invoke-RestMethod -Method POST -Body $BodyText -Uri $URI -ContentType application/x-www-form-urlencoded
$aad_access_token = $Response.access_token
# tested, I effectively have a token
# READ ml
$urllist = "https://management.azure.com/subscriptions/$subscriptionid/providers/Microsoft.MachineLearningServices/locations/westeurope/quotas?api-version=2021-03-01-preview"
$headers = #{"Authorization" = "Bearer " + $aad_access_token}
Invoke-RestMethod -Method GET -HEADERS $headers -Uri $urllist -ContentType application/x-www-form-urlencoded
I found what happend and I am a little bit confused.
The resource was empty, because I completely forgot to create a compute!

How do I get AAD profile picture URL?

In the Azure Portal, under Azure Active Directory / Users, you can find image of the user.
It's like this https://main.iam.ad.ext.azure.com/api/Images/Users/<xxx>=.jpg?t=123456
This <xxx> is kind of base64 encoded string with padding, so maybe you can convert it somehow from the object-id? I tried with no luck.
Is there a way to extract this URL through the Microsoft.Graph?
I tried to use https://graph.microsoft.com/beta/me/photo, but it's an object. And when you use https://graph.microsoft.com/beta/me/photo/$value, it's memory stream.
However, I'd like to use already created URL.
I don't think that's possible with MS Graph today. Downloading photos through Graph requires an access token so giving out a base64 encoded URL with a temporary auth token isn't something we currently do. I agree this would make embedding profile pictures in apps much easier if you can just cache the image like a static resource.
If you want to submit a feature request you can use the Microsoft Graph uservoice at https://microsoftgraph.uservoice.com/forums/920506-microsoft-graph-feature-requests
$upn = 'user#domain.com'
Connect-AzureAD
$userid = (Get-AzureADUser -ObjectId $upn).ObjectId
login-azurermaccount
$context = Get-AzureRmContext
$tenantId = $context.Tenant.Id
$refreshToken = $context.TokenCache.ReadItems().RefreshToken
$body = "grant_type=refresh_token&refresh_token=$($refreshToken)&resource=74658136-14ec-4630-ad9b-26e160ff0fc6"
$apiToken = Invoke-RestMethod "https://login.windows.net/$tenantId/oauth2/token" -Method POST -Body $body -ContentType 'application/x-www-form-urlencoded'
$header = #{
'Authorization' = 'Bearer ' + $apiToken.access_token
'Content-Type' = 'application/json'
'X-Requested-With'= 'XMLHttpRequest'
'x-ms-client-request-id'= [guid]::NewGuid()
'x-ms-correlation-id' = [guid]::NewGuid()
}
$url = "https://main.iam.ad.ext.azure.com/api/UserDetails/" + $userid
$imageurl = (Invoke-RestMethod –Uri $url –Headers $header –Method GET -Body $content -ErrorAction Stop).imageUrl
$imageurl

Call azure ad-protected API from powershell with username/password

I have an Azure AD-protected web api.
My javascript sends a callback-url where the users access-token is sent to
https://login.microsoftonline.com/{my_tenant}/oauth2/v2.0/token/?redirect_uri={my_url}&...
Now I want to access my api using powershell and for that reason I would like to just have the token as a response. I have tried this resource owner password credential-flow with the code below, but it just says that the username or password is incorrect...(I use same for manual login)
$creds = #{
client_id = $clientId
username = $username
password = $password
grant_type = "password"
scope="User.Read"
}
$headers = #{
"Content-Type"="application/x-www-form-urlencoded"
}
Invoke-RestMethod $authUrl -Method Post -Body $creds -Headers $headers;
So, in short, I want to login using username and password with powershell, is it possible?
I could not reproduce your issue, please double check your username and password.
Or you can try my working sample, and if you want to get the toekn from your own api, the scope should be {Application ID URI or Application ID}/User.Read, if you use scope="User.Read", it represents the MS Graph API by default.
Sample:
$authUrl = "https://login.microsoftonline.com/{tenant-id}/oauth2/v2.0/token/"
$clientId = "xxxxxxxxxxxxxxxxxxx"
$username = "xxxxxx#xxx.onmicrosoft.com"
$password = "xxxxxx"
$creds = #{
client_id = $clientId
username = $username
password = $password
grant_type = "password"
scope="{Application ID URI or Application ID}/User.Read"
}
$headers = #{
"Content-Type"="application/x-www-form-urlencoded"
}
Invoke-RestMethod $authUrl -Method Post -Body $creds -Headers $headers
Update:
When using resource owner password credential flow, please note the important things below.

Resources