简体   繁体   中英

Parse JWT Token to get the payload content only without external library in C# or Blazor

I am writing the client app with Blazor that has access to a JWT. I'd like to know a simple way to read the token payload content without adding additional dependency because I don't need the other information and don't need to validate the token. I think parsing the payload content should be simple enough to just write it in a method.

    JwtTokenContent ReadJwtTokenContent(string token)
    {
        var content = token.Split('.')[1];

        // Exception here, it's not a valid base64 string
        var jsonPayload = Encoding.UTF8.GetString(
            Convert.FromBase64String(content));

        Console.WriteLine(jsonPayload);

        return JsonSerializer.Deserialize<JwtTokenContent>(jsonPayload);
    }

How can I decode the payload? It doesn't seem to be just a base64 string.

The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters.

This is an example JWT token:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJJZCI6IjUyYjg3ZTUwLTViYmMtNDE0Ny1iOTMwLWY2ZGI0ZTUyNDEwYiIsIlVzZXJuYW1lIjoiZGF0dm1Ab3V0bG9vay5jb20iLCJpc3MiOiJodHRwczovL2xvY2FsaG9zdDo0NDMyMi8ifQ.4wKxDCwQ6onvNA_atndSitGjufR-tXutWq-tRNhqKzc

(content is eyJJZCI6IjUyYjg3ZTUwLTViYmMtNDE0Ny1iOTMwLWY2ZGI0ZTUyNDEwYiIsIlVzZXJuYW1lIjoiZGF0dm1Ab3V0bG9vay5jb20iLCJpc3MiOiJodHRwczovL2xvY2FsaG9zdDo0NDMyMi8ifQ )


Thanks to Kalten, here's the solution for my case:

    JwtTokenContent ReadJwtTokenContent(string token)
    {
        var content = token.Split('.')[1];
        Console.WriteLine(content);

        var jsonPayload = Encoding.UTF8.GetString(
            this.Decode(content));
        Console.WriteLine(jsonPayload);

        return JsonSerializer.Deserialize<JwtTokenContent>(jsonPayload);
    }

    byte[] Decode(string input)
    {
        var output = input;
        output = output.Replace('-', '+'); // 62nd char of encoding
        output = output.Replace('_', '/'); // 63rd char of encoding
        switch (output.Length % 4) // Pad with trailing '='s
        {
            case 0: break; // No pad chars in this case
            case 2: output += "=="; break; // Two pad chars
            case 3: output += "="; break; // One pad char
            default: throw new System.ArgumentOutOfRangeException("input", "Illegal base64url string!");
        }
        var converted = Convert.FromBase64String(output); // Standard base64 decoder
        return converted;
    }

Try this by Steve Anderson

 public static IEnumerable<Claim> ParseClaimsFromJwt(string jwt)
    {
        var payload = jwt.Split('.')[1];
        var jsonBytes = ParseBase64WithoutPadding(payload);
        var keyValuePairs = JsonSerializer.Deserialize<Dictionary<string, object>>(jsonBytes);
        return keyValuePairs.Select(kvp => new Claim(kvp.Key, kvp.Value.ToString()));
    }

    private static byte[] ParseBase64WithoutPadding(string base64)
    {
        switch (base64.Length % 4)
        {
            case 2: base64 += "=="; break;
            case 3: base64 += "="; break;
        }
        return Convert.FromBase64String(base64);
    }

Usage

var token = await GetTokenAsync();
        var identity = string.IsNullOrEmpty(token)
            ? new ClaimsIdentity()
            : new ClaimsIdentity(ServiceExtensions.ParseClaimsFromJwt(token), "jwt");

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