Using Azure CLI to authenticate with Power Apps

During the time of Dynamics CRM, there was not much cross over to Azure. But these days, Azure and Power Platform are used together more often than ever. One of the important tools for an Azure person is Azure CLI. In this post, I will show you two ways you can leverage Azure CLI to authenticate with Power Apps.

Scenario 1: LINQPad or Console App

There are times when you want to quickly run some snippet in C#. I use LINQPad to do this. If you are logged in into Az CLI, you can leverage the credentials in there through Azure Identity SDK. Sample code below.

void Main()
{
	var dc = new DumpContainer().Dump("Operation");
	var environment = Util.ReadLine("Environment URI");
	var cache = System.Runtime.Caching.MemoryCache.Default;

	var client = new ServiceClient(
		tokenProviderFunction: async f => await GetToken(environment, new AzureCliCredential(), cache, dc),
		instanceUrl: new Uri(environment),
		useUniqueInstance: true);
	dc.Content = "Get current user..";	
	client.GetMyUserId().Dump();
}

// You can define other methods, fields, classes and namespaces here
private async Task<string> GetToken(string environment, AzureCliCredential credential, System.Runtime.Caching.MemoryCache cache, DumpContainer dc)
{
	dc.Content = "Trying to get item from cache..";
	var cachedToken = cache.GetCacheItem(environment);

	if(cachedToken != null) return cachedToken.Value.ToString();
	dc.Content = "Item not found in cache. Getting token..";
	
	var accessToken = (await credential.GetTokenAsync(new TokenRequestContext(new[] { $"{environment}/.default" }))).Token;
	
	var jwtToken = new JwtSecurityTokenHandler().ReadToken(accessToken) as JwtSecurityToken;
	var expiryMinutes = (jwtToken.ValidTo - jwtToken.ValidFrom).TotalMinutes - 10;
	dc.Content = $"Setting cache expiry to {expiryMinutes} minutes..";
	cache.Add(environment, accessToken, DateTimeOffset.Now.AddMinutes(expiryMinutes));
	dc.Content = "Add token to cache..";
	return accessToken;
}

Below is the sample output when you run this code.

LINQPad Output

These are the Nuget packages I reference for this C# snippet.

Nuget Packages

As you can see, I leverage AzureCliCredential to get the token that is used in the ServiceClient‘s custom token function GetToken.

You can also use my LINQPad Driver to interact with Power Apps API bit easily, but I just wanted to show a scenario where you want to do this just using C#.

Scenario 2: PowerShell

You can also use Azure CLI to get the token for Power Apps and use it in raw HTTP request. Sample code below.

$environmentUrl = "https://ENVIRONMENT.crm.dynamics.com"

#Check if user has an active az session 
$account = az account show --query "{Tenant:tenantId,Environment:environmentName, User: user.name}" --output tsv
if($account -eq $null) {
	az login
}

# Display current user details
az ad signed-in-user show --query "{UPN: userPrincipalName, name: displayName}" --output table

#Get Access Token for Power Apps
$token = az account get-access-token --resource $environmentUrl --query accessToken --output tsv

#Do a WhoAmI request using the access token
$response = iwr "$($environmentUrl)/api/data/v9.1/WhoAmI()" -Authentication OAuth -Token $(ConvertTo-SecureString $token -AsPlainText -Force)
$whoAmIJson = ConvertFrom-Json $response.Content
Write-Output "`nUserId: $($whoAmIJson.UserId)"
Write-Output "Organization Id: $($whoAmIJson.OrganizationId)"

Below is the sample output from PowerShell 7.

The advantage of this method is that you don’t need any App Registration or OAuth password prompt. You can simply leverage the account you have in Azure CLI, that you are also using to connect to Power Apps.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s