Skip to content

Commit 9398c2f

Browse files
Merge pull request #684 from DuendeSoftware/identitymodel-oidc-utils-updates
Update documentation for IdentityModel utilities
2 parents be4f436 + 927946b commit 9398c2f

File tree

6 files changed

+804
-46
lines changed

6 files changed

+804
-46
lines changed

src/content/docs/identitymodel/utils/base64.md

Lines changed: 39 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -7,22 +7,49 @@ redirect_from:
77
- /foss/identitymodel/utils/base64/
88
---
99

10-
JWT tokens are serialized using [Base64 URL
11-
encoding](https://tools.ietf.org/html/rfc4648#section-5).
10+
:::note
11+
ASP.NET Core has built-in support for Base64 encoding and decoding via
12+
[WebEncoders.Base64UrlEncode](https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.webutilities.webencoders.base64urlencode)
13+
and
14+
[WebEncoders.Base64UrlDecode](https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.webutilities.webencoders.base64urldecode).
15+
:::
16+
17+
JWT serialization involves transforming the three core components of a JWT (Header, Payload, Signature) into a single, compact, URL-safe string. [Base64 URL encoding](https://tools.ietf.org/html/rfc4648#section-5) 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.
18+
19+
## WebEncoders Encode and Decode
20+
21+
To use the built-in .NET support, ensure you have the following package installed:
22+
23+
```bash
24+
dotnet add package Microsoft.AspNetCore.WebUtilities
25+
```
26+
27+
Then use the following code:
28+
29+
```csharp
30+
using System.Text;
31+
using Microsoft.AspNetCore.WebUtilities;
32+
33+
var bytes = "hello"u8.ToArray();
34+
var b64url = WebEncoders.Base64UrlEncode(bytes);
35+
36+
bytes = WebEncoders.Base64UrlDecode(b64url);
37+
38+
var text = Encoding.UTF8.GetString(bytes);
39+
Console.WriteLine(text);
1240

1341
IdentityModel includes the *Base64Url* class to help with
1442
encoding/decoding:
1543

1644
```csharp
17-
var text = "hello";
18-
var b64url = Base64Url.Encode(text);
45+
using System.Text;
46+
using Duende.IdentityModel;
1947

20-
text = Base64Url.Decode(b64url);
21-
```
48+
var bytes = "hello"u8.ToArray();
49+
var b64url = Base64Url.Encode(bytes);
2250

23-
:::note
24-
ASP.NET Core has built-in support via
25-
[WebEncoders.Base64UrlEncode](https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.webutilities.webencoders.base64urlencode)
26-
and
27-
[WebEncoders.Base64UrlDecode](https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.webutilities.webencoders.base64urldecode).
28-
:::
51+
bytes = Base64Url.Decode(b64url);
52+
53+
var text = Encoding.UTF8.GetString(bytes);
54+
Console.WriteLine(text);
55+
```

0 commit comments

Comments
 (0)