MongoDbTokenManager 10.2.0
dotnet add package MongoDbTokenManager --version 10.2.0
NuGet\Install-Package MongoDbTokenManager -Version 10.2.0
<PackageReference Include="MongoDbTokenManager" Version="10.2.0" />
<PackageVersion Include="MongoDbTokenManager" Version="10.2.0" />
<PackageReference Include="MongoDbTokenManager" />
paket add MongoDbTokenManager --version 10.2.0
#r "nuget: MongoDbTokenManager, 10.2.0"
#:package MongoDbTokenManager@10.2.0
#addin nuget:?package=MongoDbTokenManager&version=10.2.0
#tool nuget:?package=MongoDbTokenManager&version=10.2.0
MongoDbTokenManager
MongoDbTokenManager is an open-source C# class library designed to create, manage, and verify One-Time Tokens (OTTs). These tokens are stored in a MongoDB database, leveraging the MongoDbService package for configuration and access.
Features
- Token Generation: Generate numeric codes (e.g., for SMS) or GUID-based tokens (e.g., for email links).
- Secure Validation: Verify tokens with built-in expiration checks.
- Automatic Cleanup: Expired tokens are automatically deleted using MongoDB TTL indexes (default: 24 hours after expiry).
- Distributed & Scalable: Uses MongoDB for storage, allowing different service instances to generate and verify tokens independently.
- Strongly Typed IDs: Uses
TokenIdentifierto ensure type safety for user or resource IDs.
Getting Started
1. Install the Package
Install the NuGet package via the .NET CLI:
dotnet add package MongoDbTokenManager
2. Configuration
Configure your MongoDB connection settings in your appsettings.json or environment variables. The library uses MongoDbService which requires the following structure:
{
"MongoDbSettings": {
"ConnectionString": "mongodb://localhost:27017",
"DatabaseName": "YourDatabaseName"
}
}
3. Dependency Injection
Register the services in your Program.cs or Startup.cs:
using MongoDbTokenManager;
using MongoDbService; // Ensure this is referenced
var builder = WebApplication.CreateBuilder(args);
// Register MongoDbService (required dependency)
builder.Services.AddMongoDbService();
// Register MongoDbTokenManager services
builder.Services.AddMongoDbTokenServices();
var app = builder.Build();
Usage Example
Inject MongoDbTokenService into your class to generate and verify tokens.
using MongoDbTokenManager;
using MongoDbTokenManager.Database;
public class AuthenticationService
{
private readonly MongoDbTokenService _tokenService;
public AuthenticationService(MongoDbTokenService tokenService)
{
_tokenService = tokenService;
}
public async Task<string> SendVerificationCode(string userId)
{
// Generate a 6-digit code valid for 5 minutes (300 seconds)
var token = await _tokenService.Generate(
logId: "UserLogin",
id: new TokenIdentifier(userId),
validityInSeconds: 300,
numberOfDigits: 6
);
// If numberOfDigits is 0 (default), a GUID-based token is generated.
return token; // Send this token via SMS/Email
}
public async Task<bool> VerifyCode(string userId, string code)
{
// Verify the token.
// Returns false if token is expired or does not match.
bool isValid = await _tokenService.Validate(new TokenIdentifier(userId), code);
if (isValid)
{
// Ideally, consume the token so it cannot be used again
await _tokenService.Consume(new TokenIdentifier(userId));
}
return isValid;
}
public async Task<bool> VerifyAndConsume(string userId, string code)
{
// Convenience method to validate and consume in one step
return await _tokenService.ConsumeAndValidate(new TokenIdentifier(userId), code);
}
}
API Reference
Generate
Creates a new token or updates an existing one if valid.
logId: A string for logging purposes.id: The uniqueTokenIdentifierfor the user/resource.validityInSeconds: How long the token remains valid.numberOfDigits: (Optional) Length of the numeric code. If0, generates a GUID string.
Validate
Checks if a token is valid.
- Returns
trueif the token matches and is not expired. - Note: This package does not include brute-force protection. Implement rate limiting at your API layer if needed.
Consume
Deletes the token associated with the identifier, preventing further use.
ConsumeAndValidate
Validates the token and consumes it (deletes it) only if it matched. A wrong or expired guess leaves the stored token in place, so an incorrect attempt cannot lock the legitimate holder out. The delete is a conditional atomic operation, so of two concurrent callers submitting the same correct token exactly one receives true.
- Note: since a wrong guess no longer discards the token, repeated attempts are possible. This package does not rate limit — see the note under
Validate.
Configuration Options
Automatic Token Cleanup
Expired tokens are automatically cleaned up by MongoDB using a TTL index. By default, tokens are deleted 24 hours after expiry. You can customize this when registering the service:
// Custom cleanup: delete tokens 1 hour after expiry
builder.Services.AddSingleton(sp =>
new MongoDbTokenService(
sp.GetRequiredService<MongoService>(),
cleanupAfterExpiry: TimeSpan.FromHours(1)
));
Set to TimeSpan.Zero to delete tokens immediately upon expiry.
The TTL index is created on first use rather than at construction, so building your DI container does not require MongoDB to be reachable. Changing cleanupAfterExpiry for a collection that already has the index is applied in place.
Hardening the Stored Hash
By default a token is stored as a SHA-512 digest of the identifier and the token. The identifier acts as the salt, so it is deterministic and known — meaning that if the collection itself leaks, a short numeric token can be recovered by trying all 10ⁿ candidates offline.
Pass a hashPepper to key the digest with a secret that lives outside the database (HMAC-SHA512), which makes that offline search infeasible:
builder.Services.AddSingleton(sp =>
new MongoDbTokenService(
sp.GetRequiredService<MongoService>(),
hashPepper: builder.Configuration["TokenHashPepper"]
));
Keep the pepper in a secret store, not in appsettings.json. Note that tokens issued before you add a pepper — or with a different one — will stop validating, so roll it out when no tokens are in flight, or accept that outstanding tokens must be reissued.
Contributing
We welcome contributions! If you find a bug or have an idea for improvement, please submit an issue or a pull request on GitHub.
License
This project is licensed under the GNU GENERAL PUBLIC LICENSE.
Happy coding! 🚀
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net10.0
- Meyn.Utilities (>= 10.2.0)
- MongoDbService (>= 10.2.0)
NuGet packages (2)
Showing the top 2 NuGet packages that depend on MongoDbTokenManager:
| Package | Downloads |
|---|---|
|
SMSwitch
Package Description |
|
|
EmailSwitch
Package Description |
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 10.2.0 | 30 | 7/30/2026 |
| 10.1.0 | 494 | 12/10/2025 |
| 10.0.0 | 257 | 11/24/2025 |
| 7.0.0 | 211 | 11/23/2025 |
| 6.0.0 | 187 | 11/23/2025 |
| 5.1.0 | 264 | 6/28/2025 |
| 5.0.1 | 340 | 3/16/2025 |
| 5.0.0 | 383 | 1/8/2025 |
| 4.0.0 | 403 | 7/28/2024 |
| 3.1.0 | 215 | 7/15/2024 |
| 3.0.1 | 231 | 7/7/2024 |
| 3.0.0 | 183 | 7/7/2024 |
| 2.1.0 | 176 | 7/5/2024 |
| 2.0.0 | 191 | 6/23/2024 |
| 1.0.0 | 183 | 6/23/2024 |