将JWT(json Web令牌)转换为WebAPi中的键值对

时间:2015-08-06 19:59:06

标签: c#-4.0 dictionary oauth-2.0 asp.net-web-api2 jwt

我可以通过访问它的Autorization Header

来访问我的web api操作中的jwt
string jwt=Request.Headers.Authorization.ToString();
string jwtArray = jwt.split('.'); 

//现在我想将它的有效负载转换为Key值对。

有效载荷在jwtArray [1]中。任何人都可以建议如何将其转换为KVP。我假设JWT是Base64编码的外观。

2 个答案:

答案 0 :(得分:1)

试试这个

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

答案 1 :(得分:0)

要获得一种更清洁的方法,这是一个基于几个出色答案的帮助程序类。

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