简体   繁体   中英

Converting JWT (json Web token) into key value pairs in WebAPi

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.

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());

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM