| title | Base64 URL Encoding | ||
|---|---|---|---|
| description | Documentation for Base64 URL encoding and decoding utilities in IdentityModel, used for JWT token serialization | ||
| sidebar |
|
||
| redirect_from |
|
:::note ASP.NET Core has built-in support for Base64 encoding and decoding via WebEncoders.Base64UrlEncode and WebEncoders.Base64UrlDecode. :::
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.
To use the built-in .NET support, ensure you have the following package installed:
dotnet add package Microsoft.AspNetCore.WebUtilitiesThen 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 includes the *Base64Url* class to help with
encoding/decoding:
```csharp
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);