Skip to content

ASP.NET code validation

Eugene Fox edited this page Sep 18, 2024 · 1 revision

This tutorial shows an example on how to implement two-factor authentication creation and validation in ASP.NET web services.

First, install SimpleOTP.DependencyInjection package:

dotnet add package EugeneFox.SimpleOTP.DependencyInjection

Register Authenticator service:

// Program.cs
using SimpleOTP.DependencyInjection;
...

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddAuthenticator("My service", options =>
{
	// You can set custom options here
});

You can also define authenticator options in appsettings.json:

{
	...
	"Authenticator": {
		"Issuer": "My service",
		"Algorithm": "SHA512",
		"ToleranceSpan": {
			"Behind": 1,
			"Ahead": 1
		},
		...
	}
}
builder.Services.AddAuthenticator(builder.Configuration);

Now you can use IOtpService in your controllers and services:

using SimpleOTP;
using SimpleOTP.DependencyInjection;
...

[ApiController, Route("[controller]")]
public class MyController(IOtpService otpService) : ControllerBase
{
	private readonly IOtpService _otpService = otpService;

	[HttpPost, Route("enable2fa")]
	public IActionResult EnableTwoFactor()
	{
		var user = GetUser(); // Get current user

		// Create new secret
		using OtpSecret secret = OtpSecret.CreateNew();

		// Create configuration URI
		Uri uri = _otpService.CreateUri(user.Email, secret)

		// Save secret
		user.AuthenticatorToken = secret;
		UpdateUser(user);

		return Ok(uri.AbsoluteUri);
	}

	[HttpPost, Route("login")]
	public IActionResult Login(string code)
	{
		var user = GetUser();

		// Check if provided value is a valid code
		if (!OtpCode.TryParse(code, out OtpCode otpCode))
			return BadRequest();

		// Validate code
		if (_otpService.Validate(otpCode, user.AuthenticatorToken))
			return Ok();

		return Forbidden();
	}
}

Clone this wiki locally