Base64 URL Encoding
JWT serialization involves transforming the three core components of a JWT (Header, Payload, Signature) into a single,
compact, URL-safe string. Base64 URL encoding is used instead of
standard Base64 because it doesn’t include characters like +
, /
, or =
, making it safe to use directly in URLs and
HTTP headers without requiring further encoding.
WebEncoders Encode and Decode
Section titled “WebEncoders Encode and Decode”To use the built-in .NET support, ensure you have the following package installed:
dotnet add package Microsoft.AspNetCore.WebUtilities
Then use the following code:
using System.Text;using Microsoft.AspNetCore.WebUtilities;
var bytes = "hello"u8.ToArray();var b64url = WebEncoders.Base64UrlEncode(bytes);
bytes = WebEncoders.Base64UrlDecode(b64url);
var text = Encoding.UTF8.GetString(bytes);Console.WriteLine(text);
IdentityModel’s Base64Url
Section titled “IdentityModel’s Base64Url”IdentityModel includes the Base64Url
class to help with
encoding/decoding:
using System.Text;using Duende.IdentityModel;
var bytes = "hello"u8.ToArray();var b64url = Base64Url.Encode(bytes);
bytes = Base64Url.Decode(b64url);
var text = Encoding.UTF8.GetString(bytes);Console.WriteLine(text);