Sign in

Add a Custom Cache

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.

When to use caching

Use caching when:

  • You receive multiple requests with the same access token
  • Introspection adds noticeable latency
  • You want to reduce the number of requests to the authorization server

Before you begin

This guide assumes you've completed the installation guide.

You should already have:

  • An ASP.NET Core project
  • The MonoCloud.Authentication.Api SDK installed
  • The MonoCloud section configured in appsettings.json

Implement the IIntrospectionCache interface

The SDK caches introspection results through any implementation of IIntrospectionCache. Implementations must be registered with a singleton lifetime.

In-memory cache

InMemoryIntrospectionCache.cs
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.

Enable caching

Register your cache as a singleton and turn on caching in the options.

Program.cs
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:

  • After a successful introspection, the returned claims are stored in the cache keyed by the token
  • Subsequent requests with the same token return cached claims without re-introspecting
  • Cached entries expire after CacheDuration (default 5 minutes), and never outlive the token's expiry
© 2024 MonoCloud. All rights reserved.