Design your own OTP/TOTP Verification from scratch with ASP.NET Core & Distributed Cache
Build secure One-Time-Password(OTP)[URL link/Code] using only native C# code, Redis & memory Cache
Concepts
One-time password (OTP) provides a mechanism for one-time access with a unique token. Useful for verifying identity or for activating authentication as a strong guarantee.
Time-based One-time password (TOTP) same OTP but with during a specified period of time to expire token.
for more information Google it.
Let’s start build our Verification to generate URL & Code as TOTP scan.
Requirements:
- Visual Studio 2013 and later / VS Code, I use Visual Studio 2022
- C# 7.0 and later, I use C# 10
- .Net Core 2.2 and later, I use .Net 6.0
- Microsoft Web packages for ASP.NET Core Applications
- Installed Redis on Windows.
You can download Redis-server on windows at:
Releases · microsoftarchive/redis (github.com)
Releases · tporadowski/redis (github.com)
◦ Create Project
- Create blank solution.
- Add class library ‘’OtpVerification’ ’ for our OTP lib.
- Create Asp Net Core Web API for Example.
◦ Build OtpVerification Service (Microservice)
- Create Options class to enable shape of unique code and adjust expiration time.
- Download Microsoft.Extensions.Caching.StackExchangeRedis nuget
- Inject IDistributedCache and other services.
- Start to write Generate() code/URL & Scan() functional.
Note: you can use any TOTP algorithms to generate code and verify, I use RNGCrypto/Rfc289 8 with own hack way to Time-Based check.
Please check source code GitHub
Testing:
Add OTP Controller to Example project
- Create new user with 2 min expireTime OTP code.
- Verify user by userId and Code / URL
- Try by URL after expired
endpoints.MapGet($"/{nameof(OtpVerification)}/{{*key}},(string key)=> {vat otp = endpoints.ServiceProvider.GetRequierdService<IOtpVerification>(); if(otp.Scan(key)) return "Verify"; return "Un-Verify";});
- Refresh user OTP Then retry by URL
Closing
You can store/generate OTP code using Third-Party API, Tow-Factor.
Integrate your (Identity) Model with IEndpointRouteBuilder to Map OTP Verification and make powerful your own TOTP.
Code
You can find source code example on GitHub.