OnlineMenu.OtpAuthentication
1.0.0
dotnet add package OnlineMenu.OtpAuthentication --version 1.0.0
NuGet\Install-Package OnlineMenu.OtpAuthentication -Version 1.0.0
<PackageReference Include="OnlineMenu.OtpAuthentication" Version="1.0.0" />
<PackageVersion Include="OnlineMenu.OtpAuthentication" Version="1.0.0" />
<PackageReference Include="OnlineMenu.OtpAuthentication" />
paket add OnlineMenu.OtpAuthentication --version 1.0.0
#r "nuget: OnlineMenu.OtpAuthentication, 1.0.0"
#:package OnlineMenu.OtpAuthentication@1.0.0
#addin nuget:?package=OnlineMenu.OtpAuthentication&version=1.0.0
#tool nuget:?package=OnlineMenu.OtpAuthentication&version=1.0.0
OnlineMenu.Identity
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
๐ 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/passwordPhoneOtp(1) - Phone-based OTPEmailOtp(2) - Email-based OTPSocial(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:
- TwilioSmsProvider - Production SMS via Twilio
- 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:
- Install packages instead of using local projects
- Update namespaces:
OnlineMenu.Identity.Abstractions.AbstractionsโOnlineMenu.IdentityOnlineMenu.Infrastructure.ServicesโOnlineMenu.OtpAuthentication.Services
- 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.
๐ Related Projects
- OnlineMenu.Foundation - Domain core and multi-tenancy
- OnlineMenuSaaS - Full SaaS application
๐ฌ Support
- ๐ง Email: support@onlinemenu.com
- ๐ฌ Discussions: GitHub Discussions
- ๐ Issues: GitHub Issues
Made with โค๏ธ by the OnlineMenu team
| Product | Versions 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. |
-
net8.0
- Microsoft.EntityFrameworkCore (>= 8.0.0)
- Microsoft.EntityFrameworkCore.InMemory (>= 8.0.0)
- Microsoft.Extensions.Logging.Abstractions (>= 8.0.0)
- Npgsql.EntityFrameworkCore.PostgreSQL (>= 8.0.0)
- OnlineMenu.Identity.Abstractions (>= 1.0.0)
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 |