Skip to content

Instantly share code, notes, and snippets.

@ahelland
Created June 14, 2016 18:51
Show Gist options
  • Save ahelland/6d6aa9fbb1cd090cebee53f62adff2d7 to your computer and use it in GitHub Desktop.
Save ahelland/6d6aa9fbb1cd090cebee53f62adff2d7 to your computer and use it in GitHub Desktop.
Method to decode a JWT and pretty print the JSON contents
//Assume the input is in a control called txtJwtIn,
//and the output will be placed in a control called txtJwtOut
var jwtHandler = new JwtSecurityTokenHandler();
var jwtInput = txtJwtIn.Text;
//Check if readable token (string is in a JWT format)
var readableToken = jwtHandler.CanReadToken(jwtInput);
if(readableToken != true)
{
txtJwtOut.Text = "The token doesn't seem to be in a proper JWT format.";
}
if(readableToken == true)
{
var token = jwtHandler.ReadJwtToken(jwtInput);
//Extract the headers of the JWT
var headers = token.Header;
var jwtHeader = "{";
foreach(var h in headers)
{
jwtHeader += '"' + h.Key + "\":\"" + h.Value + "\",";
}
jwtHeader += "}";
txtJwtOut.Text = "Header:\r\n" + JToken.Parse(jwtHeader).ToString(Formatting.Indented);
//Extract the payload of the JWT
var claims = token.Claims;
var jwtPayload = "{";
foreach(Claim c in claims)
{
jwtPayload += '"' + c.Type + "\":\"" + c.Value + "\",";
}
jwtPayload += "}";
txtJwtOut.Text += "\r\nPayload:\r\n" + JToken.Parse(jwtPayload).ToString(Formatting.Indented);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment