OnlineMenu.OtpAuthentication 1.0.0

dotnet add package OnlineMenu.OtpAuthentication --version 1.0.0
                    
NuGet\Install-Package OnlineMenu.OtpAuthentication -Version 1.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="OnlineMenu.OtpAuthentication" Version="1.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="OnlineMenu.OtpAuthentication" Version="1.0.0" />
                    
Directory.Packages.props
<PackageReference Include="OnlineMenu.OtpAuthentication" />
                    
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 OnlineMenu.OtpAuthentication --version 1.0.0
                    
#r "nuget: OnlineMenu.OtpAuthentication, 1.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 OnlineMenu.OtpAuthentication@1.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=OnlineMenu.OtpAuthentication&version=1.0.0
                    
Install as a Cake Addin
#tool nuget:?package=OnlineMenu.OtpAuthentication&version=1.0.0
                    
Install as a Cake Tool

OnlineMenu.Identity

Build Status NuGet License: MIT

Authentication and identity management packages for OnlineMenu applications. Provides a complete multi-provider authentication system with OTP support, notifications, and a standalone microservice.

๐ŸŽฏ Project Status

โœ… Phase 1 Complete - Foundation packages created โœ… Phase 2 Complete - Identity packages created โœ… Phase 3 Complete - Identity microservice created and building successfully

๐Ÿ“ฆ Packages

Package Version Description
OnlineMenu.Identity.Abstractions NuGet Provider-agnostic authentication interfaces
OnlineMenu.Identity.Keycloak NuGet Keycloak OIDC implementation
OnlineMenu.Notifications NuGet SMS and email notification providers
OnlineMenu.OtpAuthentication NuGet Database-backed OTP with EF Core

๐Ÿš€ Quick Start

Installation

# Core authentication
dotnet add package OnlineMenu.Identity.Abstractions
dotnet add package OnlineMenu.Identity.Keycloak

# OTP and notifications
dotnet add package OnlineMenu.OtpAuthentication
dotnet add package OnlineMenu.Notifications

Basic Setup

using OnlineMenu.Identity.Keycloak;
using OnlineMenu.OtpAuthentication.Extensions;
using OnlineMenu.Notifications.Extensions;

var builder = WebApplication.CreateBuilder(args);

// Add Keycloak authentication
builder.Services.AddKeycloakIdentityProvider(options =>
{
    options.Authority = "https://your-keycloak.com/realms/YourRealm";
    options.ClientId = "your-client-id";
    options.ClientSecret = "your-client-secret";
});

// Add OTP authentication with PostgreSQL
builder.Services.AddOtpAuthentication(
    builder.Configuration.GetConnectionString("DefaultConnection"));

// Add Twilio SMS notifications
builder.Services.AddTwilioNotifications(options =>
{
    options.AccountSid = builder.Configuration["Twilio:AccountSid"];
    options.AuthToken = builder.Configuration["Twilio:AuthToken"];
    options.FromNumber = builder.Configuration["Twilio:FromNumber"];
});

var app = builder.Build();
app.Run();

๐Ÿ“– Documentation

OnlineMenu.Identity.Abstractions

Provider-agnostic authentication interfaces supporting multiple authentication methods.

Authentication Methods:

  • UsernamePassword (0) - Traditional username/password
  • PhoneOtp (1) - Phone-based OTP
  • EmailOtp (2) - Email-based OTP
  • Social (3) - Social login (Google, Facebook, etc.)

Core Interfaces:

public interface IIdentityProvider
{
    Task<AuthenticationResult> AuthenticateAsync(AuthenticationRequest request);
    Task<AuthenticationResult> RefreshTokenAsync(string refreshToken);
    Task<bool> RevokeTokenAsync(string token);
    Task<UserInfo?> GetUserInfoAsync(string accessToken);
}

public interface IOtpService
{
    string GenerateCode(int length = 6);
    Task StoreCodeAsync(string identifier, string code, Guid tenantId, int expiryMinutes);
    Task<bool> ValidateCodeAsync(string identifier, string code, Guid tenantId);
    Task MarkAsUsedAsync(string identifier, string code, Guid tenantId);
}

public interface INotificationService
{
    Task<bool> SendSmsAsync(string phoneNumber, string message);
    Task<bool> SendEmailAsync(string email, string subject, string body);
}

OnlineMenu.Identity.Keycloak

Keycloak implementation with full OIDC support.

Features:

  • Resource Owner Password Credentials (ROPC) flow
  • Token refresh and revocation
  • User info extraction with roles
  • OTP integration
  • Comprehensive error handling

Usage:

services.AddKeycloakIdentityProvider(options =>
{
    options.Authority = "https://keycloak.example.com/realms/MyRealm";
    options.TokenEndpoint = $"{options.Authority}/protocol/openid-connect/token";
    options.UserInfoEndpoint = $"{options.Authority}/protocol/openid-connect/userinfo";
    options.ClientId = "my-client";
    options.ClientSecret = "secret";
});

// Usage in controller
public class AuthController : ControllerBase
{
    private readonly IIdentityProvider _identityProvider;

    [HttpPost("login")]
    public async Task<IActionResult> Login([FromBody] LoginRequest request)
    {
        var authRequest = new AuthenticationRequest
        {
            AuthMethod = AuthMethod.UsernamePassword,
            Username = request.Username,
            Password = request.Password,
            TenantId = request.TenantId
        };

        var result = await _identityProvider.AuthenticateAsync(authRequest);

        if (result.IsSuccess)
        {
            return Ok(new
            {
                result.AccessToken,
                result.RefreshToken,
                result.ExpiresIn,
                result.UserInfo
            });
        }

        return Unauthorized(new { result.ErrorMessage });
    }
}

OnlineMenu.Notifications

SMS and email notification providers.

Providers:

  1. TwilioSmsProvider - Production SMS via Twilio
  2. ConsoleNotificationService - Development/testing

Usage:

// Production - Twilio
services.AddTwilioNotifications(options =>
{
    options.AccountSid = Configuration["Twilio:AccountSid"];
    options.AuthToken = Configuration["Twilio:AuthToken"];
    options.FromNumber = Configuration["Twilio:FromNumber"];
});

// Development - Console
services.AddConsoleNotifications();

// Send SMS
public class OtpController : ControllerBase
{
    private readonly INotificationService _notificationService;
    private readonly IOtpService _otpService;

    [HttpPost("send-otp")]
    public async Task<IActionResult> SendOtp([FromBody] SendOtpRequest request)
    {
        var code = _otpService.GenerateCode(6);
        await _otpService.StoreCodeAsync(
            request.PhoneNumber,
            code,
            request.TenantId,
            expiryMinutes: 5);

        var message = $"Your verification code is: {code}";
        var sent = await _notificationService.SendSmsAsync(request.PhoneNumber, message);

        return Ok(new { sent, expiresIn = 5 });
    }
}

OnlineMenu.OtpAuthentication

Database-backed OTP with Entity Framework Core.

Features:

  • Cryptographically secure code generation
  • Automatic expiry
  • Rate limiting (max attempts)
  • Multi-tenant isolation
  • IP address logging
  • Cleanup utilities

Database Setup:

// Startup.cs
services.AddOtpAuthentication(
    Configuration.GetConnectionString("DefaultConnection"));

// Run migrations
dotnet ef migrations add InitialOtp --project YourProject
dotnet ef database update --project YourProject

OTP Entity:

public class OtpCode
{
    public int Id { get; }
    public string Identifier { get; }        // Phone or email
    public string Code { get; }              // The OTP code
    public DateTime CreatedAt { get; }
    public DateTime ExpiresAt { get; }
    public bool IsUsed { get; }
    public Guid TenantId { get; }
    public int Attempts { get; }             // Attempt counter
    public int MaxAttempts { get; }          // Default: 3
    public string? IpAddress { get; }

    public bool IsValid { get; }             // !IsUsed && not expired
    public bool HasReachedMaxAttempts { get; }
}

Complete OTP Flow:

// 1. Generate and send OTP
var code = _otpService.GenerateCode(6);
await _otpService.StoreCodeAsync(phoneNumber, code, tenantId, expiryMinutes: 5);
await _notificationService.SendSmsAsync(phoneNumber, $"Code: {code}");

// 2. Verify OTP
var isValid = await _otpService.ValidateCodeAsync(phoneNumber, userCode, tenantId);
if (isValid)
{
    await _otpService.MarkAsUsedAsync(phoneNumber, userCode, tenantId);
    // Proceed with authentication
}

// 3. Cleanup (run periodically via background job)
var otpService = (DatabaseOtpService)_otpService;
await otpService.CleanupExpiredCodesAsync();

๐Ÿ—๏ธ Architecture

OnlineMenu.Identity
โ”œโ”€โ”€ Abstractions Layer
โ”‚   โ””โ”€โ”€ Provider-agnostic interfaces (IIdentityProvider, IOtpService, etc.)
โ”‚
โ”œโ”€โ”€ Implementation Layer
โ”‚   โ”œโ”€โ”€ Keycloak Provider (OIDC/OAuth2)
โ”‚   โ”œโ”€โ”€ Notification Providers (Twilio, Console)
โ”‚   โ””โ”€โ”€ OTP Service (EF Core)
โ”‚
โ””โ”€โ”€ Microservice (Optional)
    โ””โ”€โ”€ Standalone Identity API with FastEndpoints

๐Ÿ” Security Features

  • Secure OTP Generation: Cryptographic random number generator
  • Rate Limiting: Max attempts to prevent brute force
  • Automatic Expiry: Time-bound OTP codes
  • IP Logging: Security audit trail
  • Multi-Tenant Isolation: Data separated by tenant
  • Token Revocation: Logout support
  • JWT Validation: Standard claims verification

๐Ÿงช Testing

# Run all tests
dotnet test

# Unit tests
dotnet test tests/OnlineMenu.Identity.Tests

# Integration tests
dotnet test tests/OnlineMenu.IdentityService.IntegrationTests

Testing with Console Notifications:

// appsettings.Development.json
{
  "UseConsoleNotifications": true
}

// Program.cs
if (builder.Environment.IsDevelopment())
{
    builder.Services.AddConsoleNotifications();
}
else
{
    builder.Services.AddTwilioNotifications(/* ... */);
}

๐Ÿ“Š Database Schema

OtpCodes Table

CREATE TABLE "OtpCodes" (
    "Id" SERIAL PRIMARY KEY,
    "Identifier" VARCHAR(100) NOT NULL,
    "Code" VARCHAR(10) NOT NULL,
    "CreatedAt" TIMESTAMP NOT NULL,
    "ExpiresAt" TIMESTAMP NOT NULL,
    "IsUsed" BOOLEAN NOT NULL,
    "TenantId" UUID NOT NULL,
    "Attempts" INTEGER NOT NULL,
    "MaxAttempts" INTEGER NOT NULL,
    "IpAddress" VARCHAR(45)
);

CREATE INDEX "IX_OtpCodes_Identifier_TenantId_ExpiresAt"
    ON "OtpCodes" ("Identifier", "TenantId", "ExpiresAt");

๐Ÿ”„ Migration from OnlineMenuSaaS

If you're migrating from the monolithic OnlineMenuSaaS application:

  1. Install packages instead of using local projects
  2. Update namespaces:
    • OnlineMenu.Identity.Abstractions.Abstractions โ†’ OnlineMenu.Identity
    • OnlineMenu.Infrastructure.Services โ†’ OnlineMenu.OtpAuthentication.Services
  3. Update DI registration:
    // Old
    services.AddScoped<IOtpService, DatabaseOtpService>();
    
    // New
    services.AddOtpAuthentication(connectionString);
    

๐Ÿค Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

๐Ÿ“ License

This project is licensed under the MIT License - see the LICENSE file for details.

๐Ÿ’ฌ Support


Made with โค๏ธ by the OnlineMenu team

Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  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

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.0.0 83 12/28/2025