Forum Discussion
extract appid from decoded jwttoken
Hi, Rajendra.
From having a read of the following article, I quickly knocked up two functions that reliably (for me) decide the JWT. The appid field is in "proper" GUID notation.
I tested using certificate-based authentication (i.e. servicePrincipal + certificate).
For testing purposes, I obtained a token (stored in $Token) using Get-AzAccessToken.
From your sample code, what I'm seeing missing is the reversal of the two special character replacements - as per the reference documentation below.
Reference
PowerShell functions
function Get-NormalisedTokenSection
{
[cmdletbinding()]
param(
[parameter(Mandatory=$true)][ValidateNotNullOrEmpty()][string] $TokenSection
)
$Value = $TokenSection.Replace("_", "/").Replace("-", "+");
switch ($Value.Length % 4)
{
1 {
$Value += "===";
break;
}
2 {
$Value += "==";
break;
}
3 {
$Value += "=";
break;
}
}
[string]::new([System.Convert]::FromBase64String($Value)) | ConvertFrom-Json;
}
function Get-TokenSections
{
[cmdletbinding()]
param(
[parameter(Mandatory=$true)][ValidateNotNullOrEmpty()][string] $Token
)
if (3 -ne ($Sections = $Token.Split(".")).Length)
{
throw("Invalid access token.");
}
[PSCustomObject] @{
Header = Get-NormalisedTokenSection -TokenSection $Sections[0];
Claim = Get-NormalisedTokenSection -TokenSection $Sections[1];
}
}
Output (scoped down to just the appid)
Cheers,
Lain
- Rajendra605Mar 19, 2024
Microsoft
even I am using replacement , I am getting same issue .
$TokenSection.Replace("_", "/").Replace("-", "+");
actually when I am passing hard coded value in $tokensection variable , then I am able to appid in guid format else I am getting ***
- LainRobertsonMar 19, 2024Silver Contributor
The only other diagnostic I can think of is to compare tokens, as the only kind I compared against is an Azure JWT.
You're not using the value from a header, are you, which begins with "Bearer "?
Perhaps purely for the sake of testing, you can fetch a token using the Az.Accounts module, using Get-AzAccessToken, and use the Token property of the returned object to test your existing user-defined function.
Cheers,
Lain