Skip to content

Instantly share code, notes, and snippets.

@yetanotherchris
Last active September 15, 2020 14:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yetanotherchris/6f782224fa7afc7462ed27f498c8734e to your computer and use it in GitHub Desktop.
Save yetanotherchris/6f782224fa7afc7462ed27f498c8734e to your computer and use it in GitHub Desktop.
Base64 decode a JWT in C# .NET Core
// Add the following nuget package for Base64Url decoding:
// dotnet add package Microsoft.AspNetCore.WebUtilities
// This example JWT is taken from jwt.io
string jwt = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c";
string[] parts = jwt.Split('.');
foreach (string section in parts)
{
// The final (3rd) section is the JWT signature, so will appear as nonsense as it isn't JSON
byte[] bytes = WebEncoders.Base64UrlDecode(section);
string json = System.Text.Encoding.UTF8.GetString(bytes);
Console.WriteLine(json);
}
// Output:
//
// {"alg":"HS256","typ":"JWT"}
// {"sub":"1234567890","name":"John Doe","iat":1516239022}
// I�J�04IHNJ(]�O��lj~�:N�%_�u0B,×
//
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment