Skip to content

Two-Factor Authentication ​

Introduction ​

Two-factor authentication asks for a six-digit code from an authenticator app (Google Authenticator, 1Password, Authy, ...) after the password, like Laravel Fortify. Codes are time-based one-time passwords (TOTP, RFC 6238); recovery codes let a user in who lost their phone. The sample app shows the whole flow: its settings page turns it on and off, and its login asks for the code.

Installation ​

New applications have it: three columns on users, and a User model that implements ITwoFactorAuthenticatable:

csharp
public class User : Model<User>, IAuthenticatable, ITwoFactorAuthenticatable
{
    [Hidden] public string? TwoFactorSecret { get; set; }
    [Hidden] public string? TwoFactorRecoveryCodes { get; set; }
    public DateTime? TwoFactorConfirmedAt { get; set; }
}
csharp
t.Text("two_factor_secret").Nullable();
t.Text("two_factor_recovery_codes").Nullable();
t.DateTime("two_factor_confirmed_at").Nullable();

The secret and the recovery codes are stored encrypted with Crypt. dotblaze make:auth adds the login challenge (TwoFactorChallengeController, auth/TwoFactorChallenge.blade.html, and its routes).

Enabling Two-Factor Authentication ​

Turning it on takes two steps, so a user cannot lock themselves out with a mistyped secret:

csharp
await TwoFactor.Enable(user);        // a new secret and recovery codes; not active yet

Show the secret, as text and as a QR code of the otpauth:// URL, so the user can add it to their app:

html
<p>@TwoFactor.Secret(Model)</p>
<a href="@TwoFactor.QrCodeUrl(Model)">Open in an authenticator app</a>

DotBlaze does not draw QR codes; render QrCodeUrl with a QR library of your choice. Then ask for the first code from the app:

csharp
if (!await TwoFactor.Confirm(user, request.Code))
    return Back().WithErrors(new { Code = "The provided two factor authentication code was invalid." });

TwoFactor.Enabled(user) is true once it is confirmed; TwoFactor.Pending(user) while it waits for the first code. Put these pages behind password.confirm.

Recovery Codes ​

TwoFactor.RecoveryCodes(user) lists the eight codes to show the user once; TwoFactor.RegenerateRecoveryCodes(user) makes new ones. A used recovery code is replaced by a new one.

Authenticating With Two-Factor Authentication ​

The login checks the password with Auth.Validate, which does not log in. For a user with two-factor authentication it remembers them in the session and sends them to the challenge instead:

csharp
var user = await Auth.Validate(new { request.Email, request.Password });
if (user is null) return Back().WithErrors(new { Email = "These credentials do not match our records." });

if (user is ITwoFactorAuthenticatable twoFactor && TwoFactor.Enabled(twoFactor))
{
    await TwoFactor.Challenge(twoFactor, request.Remember);
    return RedirectRoute("two-factor.login");
}
await Auth.Login(user, request.Remember);

The challenge page accepts a code or a recovery code, and logs the user in when it is right:

csharp
public async Task<IActionResult> Store([FromForm] string? code, [FromForm(Name = "recovery_code")] string? recoveryCode)
{
    if (!await TwoFactor.CompleteChallenge(code, recoveryCode))
        return Back().WithErrors(new { Code = "The provided two factor authentication code was invalid." });
    return Intended("/");
}

Codes from the current 30-second step and one step either side are accepted (clock drift), each only once. Throttle the challenge route (throttle:5,1).

Disabling Two-Factor Authentication ​

csharp
await TwoFactor.Disable(user);

The Totp class (GenerateSecret, Code, Matches) is public too, for one-time codes of your own.

Complete Example: Enroll and Confirm ​

Use the Blog test project and the template's two-factor columns:

csharp
// Blog.Tests/TwoFactorEnrollmentTest.cs
using Blog.Models;
using DotBlaze;
using DotBlaze.Testing;
using Xunit;

namespace Blog.Tests;

public class TwoFactorEnrollmentTest
{
    [Fact]
    public async Task Enrollment_is_pending_until_a_valid_code_is_confirmed()
    {
        using var app = new TestApp<Program>();
        await app.RefreshDatabase();
        await app.Run(async () =>
        {
            using var clock = Date.Freeze(
                new DateTimeOffset(2030, 1, 2, 3, 4, 5, TimeSpan.Zero));
            var user = await User.Factory().Create();
            await TwoFactor.Enable(user);
            Assert.True(TwoFactor.Pending(user));
            Assert.False(TwoFactor.Enabled(user));
            Assert.False(await TwoFactor.Confirm(user, "invalid"));
            var code = Totp.Code(TwoFactor.Secret(user), Date.UtcNow);
            Assert.True(await TwoFactor.Confirm(user, code));
            Assert.True(TwoFactor.Enabled(user));
            Assert.Equal(8, TwoFactor.RecoveryCodes(user).Count);
        });
    }
}

Run dotnet test Blog.Tests --filter FullyQualifiedName~TwoFactorEnrollmentTest. The test generates the authenticator code itself only to test enrollment. Real enrollment asks the user's authenticator for it. Complete settings actions are in the sample two-factor controller; its routes require both auth and password.confirm. make:auth creates login-challenge screens, not those settings screens.