Updated 22/07/2025
Definition
“Use a token that provides clients with restricted direct access to a specific resource, in order to offload data transfer from the application.”
Simple Exammple
Using a .Net8 ASP.NET Web Application this can be added following the steps below, this App was already secured by Microsoft Identity Provider
Configure Authentication
- Install nuget
Microsoft.AspNetCore.Authentication.Cookies
at the time I used v2.3.0 - Update the builder by setting the Apps authentication. This configures “Cookie” authentication for most operations like authenticating users and handling sign-in/out. For situations requiring a user to log in, it uses OpenID Connect, typically redirecting to an external identity provider. Finally, it integrates AddMicrosoftIdentityWebApp, enabling the application to use Microsoft identity platform (like Azure Active Directory) for authentication.
1 | builder.Services.AddAuthentication(options => |
- Add
app.UseAuthentication();
which adds the Authentication Middleware to the ASP.NET Core request pipeline. This middleware is responsible for actually performing the authentication process, using the schemes configured (like the Cookie and OpenID Connect schemes in AddAuthentication above). It determines the user’s identity based on credentials (e.g., from a cookie or a token) and populates the HttpContext.User property, making the authenticated user’s information available to subsequent middleware and your application code. Without app.UseAuthentication(), even if you’ve defined authentication schemes, the application won’t actually perform the authentication checks.
Define An Ingres
- This is just the endpoint that will be accessed, note that this needs to have
[AllowAnonymous]
attribute
1 | using Microsoft.AspNetCore.Authentication; |
Key Validation
If the key is not read from a database you could encode it based on a custom Token
class, the high level steps could be:
Create a new encrypted token
- Create the object from your token class
1 | var token = new Token { |
- Get the bytes
1 | var bytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(token)); |
- Encrypt the bytes, you can use any cryptography thats decryptable (symmetric so able to be reversed). Ive seen most examples suggesting AES.
1 | var encryptedBytes = encryptionService.Encrypt(bytes); |
- Urlencode the encrypted bytes so it can be used in a query string
1 | return Base64UrlTextEncoder.Encode(encryptedBytes); |
Decrypt the token
This is the reverse of the above, thats the symmetric bit :)
- Get the bytes
1 | var bytes = Base64UrlTextEncoder.Decode(token); |
- Decrypt the bytes, see examples above
1 | var decryptedBytes = encryptionService.Decrypt(bytes); |
- Get the string value of the bytes
1 | var jsonString = Encoding.UTF8.GetString(decryptedBytes); |
- Finally deserialize
1 | return JsonConvert.DeserializeObject<ContinuationToken>(jsonString); |