Hello anonymous user,
Thanks for reaching out.
JWTs (JSON Web Tokens) are split into three pieces:
- Header - Provides information about how to validate the token including information about the type of token and how it was signed.
- Payload - Contains all of the important data about the user or app that is attempting to call your service.
- Signature - Is the raw material used to validate the token.
Each piece is separated by a period (.) and separately Base64 encoded and can be decoded using tools like https://JWT.ms , as well as any programming language. When decoding a JWT, it first needs to be converted to a Base64 encoded string from a Base64URL encoded string. Once the JWT is base64 encoded, then it needs to be decoded and later on parse that into json.
A Powershell Sample for the same:
$token = "<put the jwt here>"
if (!$token.Contains(".") -or !$token.StartsWith("eyJ")) {
Write-Error "Invalid token" -ErrorAction Stop
}
# Token
foreach ($i in 0..1) {
$data = $token.Split('.')[$i].Replace('-', '+').Replace('_', '/')
switch ($data.Length % 4) {
0 { break }
2 { $data += '==' }
3 { $data += '=' }
}
}
$decodedToken = [System.Text.Encoding]::UTF8.GetString([convert]::FromBase64String($data)) | ConvertFrom-Json
Write-Verbose "JWT Token:"
Write-Verbose $decodedToken
C# sample:
static void jwtDecoder()
{
try
{
Console.WriteLine("JWT to Decode: " + jwtEncodedString + "\n");
var jwtHandler = new JwtSecurityTokenHandler();
var readableToken = jwtHandler.CanReadToken(jwtEncodedString);
if (readableToken != true)
{
Console.WriteLine("\n\nThe token doesn't seem to be in a proper JWT format.\n\n");
}
if (readableToken == true)
{
var token = jwtHandler.ReadJwtToken(jwtEncodedString);
var headers = token.Header;
var jwtHeader = "{";
foreach (var h in headers)
{
jwtHeader += '"' + h.Key + "\":\"" + h.Value + "\",";
}
jwtHeader += "}";
Console.Write("\nHeader :\r\n" + JToken.Parse(jwtHeader).ToString(Formatting.Indented));
var claims = token.Claims;
var jwtPayLoad = "{";
foreach (Claim c in claims)
{
jwtPayLoad += '"' + c.Type + "\":\"" + c.Value + "\",";
}
jwtPayLoad += "}";
Console.Write("\r\nPayload :\r\n" + JToken.Parse(jwtPayLoad).ToString(Formatting.Indented));
var jwtSignature = "[RawSignature: ";
jwtSignature += token.RawSignature;
jwtSignature += " ]";
Console.Write("\r\nSignature :\r\n" + jwtSignature);
//Console.ReadLine();
}
}
finally
{
Console.Write("\n\nPress Enter to close window ...");
Console.Read();
}
}
-----
Please "Accept the answer" if the information helped you. This will help us and others in the community as well.