---
title: "Encrypt a local client token cache in C#"
url: https://recursiveai.org/onemodelcontext/cookbook/protect-file-based-client-token-cache/
description: "Encrypt a local OAuth client token cache in C# with OneModelContext’s FileTokenStore and a host-supplied protector. Run offline with a sample token."
version: "1.0.2"
---

# Encrypt a local client token cache 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.

[NuGet](https://www.nuget.org/packages/RecursiveAI.OneModelContext) · [GitHub](https://github.com/recursive-ai-oss/onemodelcontext-csharp) · [Docs](https://recursiveai.org/onemodelcontext/docs/) · [Download example (.zip)](https://recursiveai.org/onemodelcontext/cookbook/protect-file-based-client-token-cache/protect-file-based-client-token-cache.zip)

A Model Context Protocol® client connects an app to a server’s tools and can save OAuth tokens on disk so users don’t have to sign in each time the app starts.

Pass a protector to `FileTokenStore` to encrypt OAuth tokens before they reach disk. This offline example uses a sample token and keeps the encryption key in memory for one run.

```shell
dotnet add package RecursiveAI.OneModelContext
```

Requires [.NET 10](https://dotnet.microsoft.com/download/dotnet/10.0) (net10.0); .NET 9 and earlier aren’t supported.

Add this to an `<ItemGroup>` in your `.csproj` for ASP.NET Core Data Protection. The zip already includes it.

```xml
<FrameworkReference Include="Microsoft.AspNetCore.App" />
```

```csharp
using Microsoft.AspNetCore.DataProtection;
using RecursiveAI.OneModelContext.OAuth;

var provider = new EphemeralDataProtectionProvider();
var protection = provider.CreateProtector("TokenCache");
var dir = Directory.CreateTempSubdirectory();
try
{
    using var cache = new FileTokenStore(
        Path.Combine(dir.FullName, "tokens.bin"),
        new CacheProtector(protection));
    await cache.SetAsync("fixture",
        new() { AccessToken = "demo-token" }, default);
    var record = await cache.GetAsync("fixture", default);
    Console.WriteLine(record?.AccessToken == "demo-token"
        ? "Token recovered" : "Token missing");
}
finally { dir.Delete(recursive: true); }

sealed class CacheProtector(IDataProtector protector)
    : ITokenProtector
{
    public byte[] Protect(byte[] plain) =>
        protector.Protect(plain);
    public byte[] Unprotect(byte[] cipher) =>
        protector.Unprotect(cipher);
}
```

Unzip [the example](https://recursiveai.org/onemodelcontext/cookbook/protect-file-based-client-token-cache/protect-file-based-client-token-cache.zip), then `dotnet run`.

Writes a protected file in a temporary directory, reads the token back, and deletes the directory. It prints:

```text
Token recovered
```

To use the protected `cache` with a real client, pass `new OAuthClientOptions(serverUri) { Store = cache }` to `OAuthClient`, where `serverUri` is the server’s `Uri`.

## The full program

The program closes the writer and opens the file with a new store using the same protector. It then tries a different key: an unreadable file reads as empty, but a write throws `IOException` and leaves the original bytes in place.

The [OAuth client docs](https://recursiveai.org/onemodelcontext/docs/oauth-client/#token-stores) note that “File ownership is not checked”; keep the cache in a directory only the intended user can read and verify ownership yourself if your app depends on it.

```csharp
using Microsoft.AspNetCore.DataProtection;
using RecursiveAI.OneModelContext.OAuth;

var provider = new EphemeralDataProtectionProvider();
var protection = provider.CreateProtector("TokenCache");
var dir = Directory.CreateTempSubdirectory();
try
{
    var path = Path.Combine(dir.FullName, "tokens.bin");
    var protector = new CacheProtector(protection);
    var fixture = new TokenRecord
    {
        AccessToken = "demo-token",
        RefreshToken = "demo-refresh"
    };

    using (var writer = new FileTokenStore(path, protector))
        await writer.SetAsync("fixture", fixture, default);

    byte[] saved = File.ReadAllBytes(path);
    using var cache = new FileTokenStore(path, protector);
    var record = await cache.GetAsync("fixture", default);
    if (record?.AccessToken != fixture.AccessToken ||
        record.RefreshToken != fixture.RefreshToken)
        throw new InvalidOperationException("Fixture did not round-trip.");
    Console.WriteLine("Both tokens recovered");

    var otherProvider = new EphemeralDataProtectionProvider();
    var otherProtector = new CacheProtector(
        otherProvider.CreateProtector("TokenCache"));
    using var wrongKey = new FileTokenStore(path, otherProtector);
    if (await wrongKey.GetAsync("fixture", default) is not null)
        throw new InvalidOperationException("Wrong key read the cache.");

    try
    {
        await wrongKey.SetAsync("fixture", fixture, default);
        throw new InvalidOperationException("Wrong key wrote the cache.");
    }
    catch (IOException) when (saved.SequenceEqual(File.ReadAllBytes(path)))
    {
        Console.WriteLine("Wrong key: write refused, file unchanged");
    }
}
finally { dir.Delete(recursive: true); }

sealed class CacheProtector(IDataProtector protector)
    : ITokenProtector
{
    public byte[] Protect(byte[] plain) =>
        protector.Protect(plain);
    public byte[] Unprotect(byte[] cipher) =>
        protector.Unprotect(cipher);
}
```

```text
Both tokens recovered
Wrong key: write refused, file unchanged
```

## Variations

### Keep the token in memory instead

Use this when you don’t need to keep tokens after the process exits. The code doesn’t use Data Protection or write a cache file.

```csharp
using RecursiveAI.OneModelContext.OAuth;

var cache = new MemoryTokenStore();
await cache.SetAsync("fixture",
    new() { AccessToken = "demo-token" }, default);
var record = await cache.GetAsync("fixture", default);
Console.WriteLine(record?.AccessToken == "demo-token"
    ? "Token recovered" : "Token missing");
```

```text
Token recovered
```

## Related recipes

- [Sign in with OAuth to a protected server](https://recursiveai.org/onemodelcontext/cookbook/sign-in-to-a-protected-server/)
- [Connect to a server in C#](https://recursiveai.org/onemodelcontext/cookbook/connect-to-a-server/)

## The short answer

Pass an `ITokenProtector` as the second argument to `FileTokenStore`, then use that store for `OAuthClientOptions.Store`. The host supplies the encryption; OneModelContext sends the whole serialized cache to `Protect` before writing it and calls `Unprotect` when reading it. The sample exercises those calls directly without connecting to a server or printing any token values.

## Where should access tokens be stored?

If the client can sign in again when it starts, keep its tokens in memory. `MemoryTokenStore` is the default in OneModelContext and doesn’t write a file. If the client needs to resume a session later, use a separate, private cache file for each user. Choose the path explicitly: the temporary directory in this example is only for the offline run.

With no protector, the file contains JSON. On Unix the store writes its file with mode `0600` in a `0700` directory it creates, but permissions aren’t encryption. The file can hold client registration secrets and refresh tokens as well as access tokens. Protecting the whole file keeps those fields out of plaintext on disk; it doesn’t stop the running client from reading them, because it needs the decrypted values to make requests and refresh credentials.

## What are the best practices for storing OAuth tokens?

For an encrypted cache you want to reopen after a restart, keep the ability to decrypt it across restarts. The [ephemeral Data Protection provider](https://learn.microsoft.com/en-us/aspnet/core/security/data-protection/implementation/key-storage-ephemeral?view=aspnetcore-10.0) in this example can only reopen files protected by that same provider instance. In an app, use a host-managed key that survives a restart, or configure [a persistent Data Protection key ring with protection at rest](https://learn.microsoft.com/en-us/aspnet/core/security/data-protection/implementation/key-encryption-at-rest?view=aspnetcore-10.0). Keep the key protected separately from the cache and use the same protector purpose (`TokenCache` in the example) when reopening it.

Use a new cache path if you’re switching from an unencrypted file to an encrypted one. Attaching a protector doesn’t convert old JSON: the store can’t decrypt that file and refuses to overwrite it. For an existing encrypted cache that suddenly reads as empty, check that the original key and purpose are still available before discarding the file. If the key is gone for good, sign in again with a new cache rather than falling back to plaintext.
