Design your own OTP/TOTP Verification from scratch with ASP.NET Core & Distributed Cache

Huzaifa Aseel
3 min readJan 27, 2022

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:

  1. Visual Studio 2013 and later / VS Code, I use Visual Studio 2022
  2. C# 7.0 and later, I use C# 10
  3. .Net Core 2.2 and later, I use .Net 6.0
  4. Microsoft Web packages for ASP.NET Core Applications
  5. Installed Redis on Windows.
You can download Redis-server on windows at:
Releases · microsoftarchive/redis (github.com)
Releases · tporadowski/redis (github.com)

◦ Create Project

  1. Create blank solution.
  2. Add class library ‘’OtpVerification’ ’ for our OTP lib.
  3. Create Asp Net Core Web API for Example.

◦ Build OtpVerification Service (Microservice)

  1. Create Options class to enable shape of unique code and adjust expiration time.
  2. Download Microsoft.Extensions.Caching.StackExchangeRedis nuget
  3. Inject IDistributedCache and other services.
  4. Start to write Generate() code/URL & Scan() functional.

Please read more about Caching and Redis

screenshot of OTP verification service
Prototype OTP Generate & TOTP Scan

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

OTP routes
  • Create new user with 2 min expireTime OTP code.
  • Verify user by userId and Code / URL
Create new user — return OTP code and URL
Confirm user 48 by code before expire
  • 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";});

un-verify user 48
  • Refresh user OTP Then retry by URL
verify user 48 by new OTP

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.

--

--

Huzaifa Aseel

Software Engineer | BE-Informatics Engineering | .Net Developer | Backend Developer/FullStack | Desktop Developer | R&D