Last active
November 4, 2018 01:47
-
-
Save frankhu-2021/f3fbd8af568189406f50879077be2a0b to your computer and use it in GitHub Desktop.
Prettify JWT token to be readable
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System.IdentityModel.Tokens.Jwt; | |
| static async Task prettyJWTPrint(String myToken) | |
| { | |
| //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 = myToken; | |
| String prettyPrint = ""; | |
| //Check if readable token (string is in a JWT format) | |
| var readableToken = jwtHandler.CanReadToken(jwtInput); | |
| if (readableToken != true) | |
| { | |
| Console.WriteLine("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 += "}"; | |
| prettyPrint = "Header:\r\n" + JToken.Parse(jwtHeader).ToString(Formatting.Indented); | |
| //Extract the payload of the JWT | |
| var claims = token.Claims; | |
| var jwtPayload = "{"; | |
| foreach (System.Security.Claims.Claim c in claims) | |
| { | |
| jwtPayload += '"' + c.Type + "\":\"" + c.Value + "\","; | |
| } | |
| jwtPayload += "}"; | |
| prettyPrint += "\r\nPayload:\r\n" + JToken.Parse(jwtPayload).ToString(Formatting.Indented); | |
| } | |
| Console.WriteLine(prettyPrint); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment