How To Parse a JWT token

2 במרץ 2014

no comments

I had to create a test that retrieves a JWT token from WAAD so I created a little class that parses and displays the token content.
Here is the code:

class TokenHelper
    public static Encoding TextEncoding = Encoding.UTF8;

    private static char Base64PadCharacter = '=';
    private static char Base64Character62 = '+';
    private static char Base64Character63 = '/';
    private static char Base64UrlCharacter62 = '-';
    private static char Base64UrlCharacter63 = '_';

    public static void DisplayAccessToken(string accessToken)
        var tokenParts = accessToken.Split('.');

        if (tokenParts.Length != 3)
            throw new ApplicationException
                ("JWT Token must have three parts separated by '.' characters.");

        string encodedHeader = tokenParts[0];
        string encodedPayload = tokenParts[1];
        string signature = tokenParts[2];

        string decodedHeader = Base64Decode(encodedHeader);
        string decodedPayload = Base64Decode(encodedPayload);

        JavaScriptSerializer serializer = new JavaScriptSerializer();

        Dictionary<string, string> header = 
            serializer.Deserialize<Dictionary<string, string>>(decodedHeader);
        Dictionary<string, string> payload = 
            serializer.Deserialize<Dictionary<string, string>>(decodedPayload);

        foreach (KeyValuePair<string, string> itemPair in payload)
            Console.WriteLine("Claim: {0}  Value: {1}", itemPair.Key, itemPair.Value);

    private static byte[] DecodeBytes(string arg)
        if (String.IsNullOrEmpty(arg))
            throw new ApplicationException("String to decode cannot be null or empty.");

        StringBuilder s = new StringBuilder(arg);
        s.Replace(Base64UrlCharacter62, Base64Character62);
        s.Replace(Base64UrlCharacter63, Base64Character63);

        int pad = s.Length % 4;
        s.Append(Base64PadCharacter, (pad == 0) ? 0 : 4 - pad);

        return Convert.FromBase64String(s.ToString());

    private static string Base64Decode(string arg)
        return TextEncoding.GetString(DecodeBytes(arg));

Hope this helps


Add comment
facebook linkedin twitter email

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>