1

I can access jwt inside my web api action by accessing it's Autorization Header

string jwt=Request.Headers.Authorization.ToString();
string jwtArray = jwt.split('.'); 

//Now i want to convert it's payload into Key value pair.

The payload is in jwtArray[1]. Can anyone suggest how this can be converted into a KVP. I am assuming the JWT is Base64 encoded by the look of it.

2 Answers 2

1

Try this

var parts = token.Split('.');
string partToConvert = parts[1];
partToConvert = partToConvert.Replace('-', '+');
partToConvert = partToConvert.Replace('_', '/');
switch (partToConvert.Length % 4)
{
  case 0:
      break;
  case 2:
      partToConvert += "==";
      break;
  case 3:
      partToConvert += "=";
      break;
}
var partAsBytes = Convert.FromBase64String(partToConvert);
var partAsUTF8String = Encoding.UTF8.GetString(partAsBytes, 0, partAsBytes.Count());
// You would need Json .NET for the below
var jwt = JObject.Parse(partAsUTF8String);
var dictionary = JsonConvert.DeserializeObject<Dictionary<string, object>>(jwt.ToString());
Sign up to request clarification or add additional context in comments.

Comments

0

For a cleaner approach to this, Here's a helper class based on a couple of brilliant answers.

public static class StringExtensions
{
    /// <summary>
    /// Convert a normal string to base64
    /// </summary>
    /// <param name="text">Original String</param>
    /// <returns></returns>
    /// <remarks>
    /// Original Source: https://stackoverflow.com/a/60738564/8058709
    /// </remarks>
    public static string EncodeToBase64(this string text)
    {
        return Convert.ToBase64String(Encoding.UTF8.GetBytes(text))
            .TrimEnd('=').Replace('+', '-')
            .Replace('/', '_');
    }

    /// <summary>
    /// Convert a base64 string to a normal one
    /// </summary>
    /// <param name="payload">Base64 string</param>
    /// <returns>A normal string</returns>
    /// <remarks>
    /// Original Source: https://stackoverflow.com/a/60738564/8058709
    /// </remarks>
    public static string DecodeFromBase64(this string payload)
    {
        payload = payload.Replace('_', '/').Replace('-', '+');
        switch (payload.Length % 4)
        {
            case 2:
                payload += "==";
                break;
            case 3:
                payload += "=";
                break;
        }
        return Encoding.UTF8.GetString(Convert.FromBase64String(payload));
    }

    /// <summary>
    /// Decode a JWT payload to a dictionary
    /// </summary>
    /// <param name="jwt">JWT payload</param>
    /// <returns>
    /// A dictionary representation of the jwt string
    /// </returns>
    /// <remarks>
    /// Inspiration: https://stackoverflow.com/a/31878953/8058709
    /// </remarks>
    public static IDictionary<string, object> DecodeJwt(this string jwt)
    {
        string[] chunks = jwt.Split('.');

        string data = DecodeFromBase64(chunks.ElementAtOrDefault(1));
        return JsonConvert.DeserializeObject<Dictionary<string, object>>(data);
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.