silent
silent

Reputation: 16128

Acquire Azure Active Directory resource access token from powershell for current user?

Is there a way to acquire an Azure Active Directory based token for a certain Azure Resource (in my case Time Series Insights) using PowerShell? Not for some service principle but for the current user. In .NET (c#) that's by now very easily doable be using Managed Service Identity:

using Microsoft.Azure.Services.AppAuthentication;

var azureServiceTokenProvider = new AzureServiceTokenProvider();
string token = await azureServiceTokenProvider.GetAccessTokenAsync("https://api.timeseries.azure.com/");

So is this something that would also be doable in PowerShell? Any example I have seen so far always uses either Service Principles or just gives me tokens for the Azure management APIs for the current user.

Upvotes: 1

Views: 2942

Answers (1)

andresm53
andresm53

Reputation: 2083

If your PowerShell script runs on a machine that is joined to the Active Directory on premises domain, the machine is connected to the enterprise network, and the user who runs the script is a domain user synchronized to Azure Active Directory, then you can use an override of ADAL AcquireTokenAsync which uses integrated Windows authentication.

This PowerShell example acquires a token for the current user to call Graph:

add-type -path "\Microsoft.IdentityModel.Clients.ActiveDirectory.3.13.4\lib\net45\Microsoft.IdentityModel.Clients.ActiveDirectory.dll"
$clientId = "1950a258-227b-4e31-a9cf-717495945fc2"
$resourceAppIdURI = "https://graph.windows.net"
$UserCredential = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.UserCredential" -ArgumentList "[email protected]"
$authority = "https://login.windows.net/TENANT.onmicrosoft.com" 
$authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" -ArgumentList $authority,$false
$authResult = [Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContextIntegratedAuthExtensions]::AcquireTokenAsync($authContext,$resourceAppIdURI,$clientId,$UserCredential).result

In the the example, the client ID is the well-known PowerShell GUID, and the resource is AAD Graph. If you need to call another API (i.e. Time Series Insights) you will need to register a new application (a native application) that represents the script (you need to specify the GUID of this new application in the script, $clientId variable) and give it delegated permissions to call the API. Also make sure to specify your tenant name in the $authority variable, and the API GUID or URI in the $resourceAppIdURI variable.

Upvotes: 1

Related Questions