Recursive AI

Store authorization grants in SQLite in C#

OneModelContext is a free, open-source .NET SDK for the Model Context Protocol® from Recursive AI. MIT or Apache-2.0, no native dependencies.

Save OAuth authorization grants across restarts in a SQLite-compatible file on one machine. This example uses OneLite, Recursive AI’s managed SQLite-compatible engine, not Microsoft.Data.Sqlite; standard SQLite 3.53.1 opened the resulting grants.db and read the grant.

Terminal
dotnet add package RecursiveAI.OneModelContext.OneLite

Requires .NET 10 (net10.0); .NET 9 and earlier aren’t supported.

Terminal
# In the downloaded project
dotnet run

Unzip the example, then dotnet run.

Text
Saved a grant in grants.db.
After reopen: Redeemed
Scope: notes:read
Second redemption: AlreadyRedeemed

The full program

OneLiteAuthorizationStore.OpenAsync creates grants.db and its tables if they’re missing. The program saves an authorization-code grant for the fictional user demo-user with the scope notes:read, closes the file, and reopens it before redeeming. The sample values are defined in Program.cs; it doesn’t contact an authorization server or issue tokens.

If the database stays locked longer than OneLite is allowed to wait, OneLite throws OneLiteException. Keep the database on local disk and restrict access to the file: the store hashes codes, refresh tokens, and client secrets, but grant metadata such as the subject and scope is stored in database columns.

C#
using System.Buffers.Text;
using System.Security.Cryptography;
using RecursiveAI.OneModelContext.Auth.Server;
using RecursiveAI.OneModelContext.OneLite;
 
const string path = "grants.db";
string codeHash = Base64Url.EncodeToString(SHA256.HashData("demo-code"u8));
var now = DateTimeOffset.UtcNow;
 
if (args is [] or ["save"])
{
    await using var store = await OneLiteAuthorizationStore.OpenAsync(path);
    await store.SaveCodeAsync(new AuthorizationCodeGrant
    {
        CodeHash = codeHash,
        ClientId = "demo-client",
        Subject = "demo-user",
        Scope = "notes:read",
        RedirectUri = "https://client.example/callback",
        Resource = "https://notes.example/context",
        CodeChallenge = Base64Url.EncodeToString(SHA256.HashData(
            "demo-verifier-used-only-in-this-storage-example"u8)),
        FamilyId = Guid.NewGuid().ToString("N"),
        ExpiresAt = now.AddMinutes(5),
        FamilyExpiresAt = now.AddDays(1)
    }, CancellationToken.None);
    Console.WriteLine("Saved a grant in grants.db.");
}
 
if (args is [] or ["redeem"])
{
    await using var store = await OneLiteAuthorizationStore.OpenAsync(path);
    var first = await store.RedeemCodeAsync(codeHash, now, CancellationToken.None);
    Console.WriteLine($"After reopen: {first.Status}");
    if (first.Grant is not null && first.Status == RedemptionStatus.Redeemed)
        Console.WriteLine($"Scope: {first.Grant.Scope}");
    var again = await store.RedeemCodeAsync(codeHash, now, CancellationToken.None);
    Console.WriteLine($"Second redemption: {again.Status}");
}

Variations

Save and redeem in separate processes

Run these commands in the same example directory, within the grant’s five-minute lifetime:

Terminal
dotnet run -- save
dotnet run -- redeem

The two commands together print the same four lines shown above. The second process reads the first process’s grants.db.


The short answer

Use OneLiteAuthorizationStore from the RecursiveAI.OneModelContext.OneLite package for a C# authorization server on one host. It implements IAuthorizationStore, which is the type accepted by AuthorizationServerOptions.Store. Open the database on startup, supply that store when constructing your authorization server, and keep it open for the server’s lifetime. Your host still provides user sign-in and consent. The file makes the server’s state durable; it doesn’t take over authorization decisions.

What authorization grants does the database store?

The authorization store is for the server that issues tokens. It keeps registered clients, authorization-code grants, refresh-token grants, revocations, and assertion identifiers. A code grant records information such as the client, subject, scope, resource, expiration, and whether the code was redeemed. The client’s cache of tokens it obtained from a server is separate, as is a store for protocol tasks.

The demonstration calls the storage methods directly to show that redemption still works after reopening the file. A running authorization server normally handles the exchange instead: it validates the token request and uses the store to mark the code as spent. Directly calling RedeemCodeAsync in the demo doesn’t perform that request validation or mint a token. The one-time change happens inside a write transaction, so opening another connection doesn’t let a code be redeemed twice. An already-spent code stays on record until the shared expiration date for the refresh tokens issued from that grant.

Can two authorization servers share the same SQLite file?

Several processes on the same machine can use the same file on local disk. OneLite’s write-ahead-log locking lets one write transaction hold the file’s write lock at a time. A writer that can’t acquire that lock within the time it’s allowed to wait (five seconds by default) fails rather than waiting indefinitely. Don’t share the file across machines or put it on a network disk; for multiple hosts, use a database provider that supports that deployment model.

The package creates and versions its own ModelContext… tables when opening the file. It leaves application tables and PRAGMA user_version alone. If your application already owns an open OneLite database connection, AttachAsync uses that connection and leaves it open when the store is disposed. Periodic purging is the authorization server’s job; a direct store demo like this one doesn’t run that server loop.

All onemodelcontext recipes