This guide shows how to cache access token introspection results to avoid re-introspecting the same token on every request.
Only tokens validated via introspection are cached.
Use caching when:
This guide assumes you've completed the installation guide.
You should already have:
MonoCloud.Authentication.Api SDK installedMonoCloud section configured in appsettings.jsonThe SDK caches introspection results through any implementation of IIntrospectionCache. Implementations must be registered with a singleton lifetime.
using Microsoft.Extensions.Caching.Memory;
using MonoCloud.Authentication.Api.Shared;
public class InMemoryIntrospectionCache : IIntrospectionCache
{
private readonly IMemoryCache _cache;
public InMemoryIntrospectionCache(IMemoryCache cache)
{
_cache = cache;
}
public Task<string?> GetAsync(string key, CancellationToken cancellationToken)
{
return Task.FromResult(_cache.Get<string>(key));
}
public Task SetAsync(string key, string value, TimeSpan expiresIn, CancellationToken cancellationToken)
{
_cache.Set(key, value, expiresIn);
return Task.CompletedTask;
}
}
How the interface works:
GetAsync(key, cancellationToken) — returns the cached value for a token, or null if it does not exist or has expired.SetAsync(key, value, expiresIn, cancellationToken) — stores an introspection result. expiresIn is how long the entry should live before it is revalidated.Register your cache as a singleton and turn on caching in the options.
using MonoCloud.Authentication.Api;
using MonoCloud.Authentication.Api.Shared;
using MonoCloud.Authentication.Api.Shared.ClientAuth;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddMemoryCache();
builder.Services.AddSingleton<IIntrospectionCache, InMemoryIntrospectionCache>();
builder.Services
.AddAuthentication(MonoCloudAuthenticationDefaults.AuthenticationScheme)
.AddMonoCloudAuthentication(options =>
{
options.TenantDomain = builder.Configuration["MonoCloud:TenantDomain"];
options.Audience = builder.Configuration["MonoCloud:Audience"];
options.ClientId = builder.Configuration["MonoCloud:ClientId"];
options.ClientAuth = new ClientSecretAuth(builder.Configuration["MonoCloud:ClientSecret"]!);
options.EnableCaching = true;
options.IntrospectJwtTokens = true;
});
builder.Services.AddAuthorization();
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapGet("/api/data", () => "Protected data")
.RequireAuthorization();
app.Run();
How it works:
CacheDuration (default 5 minutes), and never outlive the token's expiry