MongoDbTokenManager 10.0.0

There is a newer version of this package available.
See the version list below for details.
dotnet add package MongoDbTokenManager --version 10.0.0
                    
NuGet\Install-Package MongoDbTokenManager -Version 10.0.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="MongoDbTokenManager" Version="10.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="MongoDbTokenManager" Version="10.0.0" />
                    
Directory.Packages.props
<PackageReference Include="MongoDbTokenManager" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add MongoDbTokenManager --version 10.0.0
                    
#r "nuget: MongoDbTokenManager, 10.0.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package MongoDbTokenManager@10.0.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=MongoDbTokenManager&version=10.0.0
                    
Install as a Cake Addin
#tool nuget:?package=MongoDbTokenManager&version=10.0.0
                    
Install as a Cake Tool

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 and maximum attempt limits (default: 5 attempts).
  • Distributed & Scalable: Uses MongoDB for storage, allowing different service instances to generate and verify tokens independently.
  • Strongly Typed IDs: Uses TokenIdentifier to 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
        // - Token does not match
        // - Maximum validation attempts (5) have been exceeded
        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 unique TokenIdentifier for the user/resource.
  • validityInSeconds: How long the token remains valid.
  • numberOfDigits: (Optional) Length of the numeric code. If 0, generates a GUID string.

Validate

Checks if a token is valid.

  • Returns true if the token matches, is not expired, and attempt limit is not reached.
  • Note: Allows up to 5 validation attempts. After that, the token becomes invalid regardless of correctness.

Consume

Deletes the token associated with the identifier, preventing further use.

ConsumeAndValidate

Validates the token and immediately consumes it (deletes it) regardless of the result. Useful for strict one-time-use scenarios.

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 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. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (1)

Showing the top 1 NuGet packages that depend on MongoDbTokenManager:

Package Downloads
EmailSwitch

Package Description

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
10.1.0 412 12/10/2025
10.0.0 215 11/24/2025
7.0.0 175 11/23/2025
6.0.0 151 11/23/2025
5.1.0 234 6/28/2025
5.0.1 311 3/16/2025
5.0.0 352 1/8/2025
4.0.0 368 7/28/2024
3.1.0 175 7/15/2024
3.0.1 195 7/7/2024
3.0.0 151 7/7/2024
2.1.0 143 7/5/2024
2.0.0 150 6/23/2024
1.0.0 147 6/23/2024