Parsing JSON tokens in a Logic App

I created this as part of my previous post. Didn’t want to digress there by tacking this to the end of it, so here’s a separate post.

In the previous post I had got my Logic App to consume the Azure AD bearer token used to authenticate against it. How can I parse that though? Here’s what I did, am sure there are other more succint ways too.

First off, one has to parse the Headers. This is JSON, with the following schema:

I got this by looking at the Headers sent to a Logic App by making it return the Headers as response.

So, step 1: parse the Headers using this schema.

Capture the “Authorization” key into a variable.

Then create a new variable called “BearerToken” that has just the token. “Authorization” key is of the format “Bearer xxx” so I split along the space and get the second element. Here’s the expression I am using: split(variables('AuthorizationHeader'),' ')[1]

Next I need to get the body from the token. The token is split up of three dot separated parts – hhhh.bbbb.ssss – the headers, body, and signature. We need the body. So split this along the dot, get the second element.

The expression is: split(variables('BearerToken'),'.')[1]

Ideally the next step would be to decode this text (which is Base64) and parse that. But I ran into an issue. Whenever I’d parse the JSON I kept getting this error: 'The template language function 'base64ToString' was invoked with a parameter that is not valid. The value cannot be decoded from base64 representation

Then I remembered an issue I had when parsing JSON from a Base64 decoded string in PowerShell. If the Base64 string isn’t a multiple of 4 PowerShell fails when decoding. Maybe it was the same issue here… so I added some logic to check if the string length is a multiple of 4 and if not add some ‘=’ characters (doesn’t matter what you add).

The expression is: mod(length(variables('BearerTokenBody')),4)

Finally I parse the token using the following schema:

And that’s it, now I can see all the claims:

Interestingly, one of the claims is appid. I was curious what this is… turns out it is “7ab7862c-4c57-491e-8a45-d52a7e023983” in my case. Googling on that gives me the impression this is a standard id. I know, for example, Graph has an id of “00000003-0000-0000-c000-000000000000” and in the past I’ve found some more ids in a blog post, so this must be similar. That’s how I am able to authenticate in Power Automate without creating an App Registration, it must be using a well known App Id from Microsoft.

Update: See this post for what the Id is.