Skip to content

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.

In newer .NET versions, you can use the Base64Url class found in the System.Buffers.Text namespace to decode Base64 payloads using the DecodeFromChars method:

using System.Buffers.Text;
var jsonString = Base64Url.DecodeFromChars(payload);

Encoding can be done using the EncodeToString method:

using System.Buffers.Text;
var bytes = Encoding.UTF8.GetBytes("some string);
var encodedString = Base64Url.EncodeToString(bytes);

Alternatively, ASP.NET Core has built-in support for Base64 encoding and decoding via WebEncoders.Base64UrlEncode and WebEncoders.Base64UrlDecode.

To use these methods, ensure you have the following package installed:

Terminal window
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);