Skip to the content
OrielDocs
0.1.0-alpha.15GitHub

Security

Two-factor login

Ask for a second factor after the password: a 6-digit code sent by email, or one from an authenticator app, with one-time recovery codes for when the phone or the mailbox is gone.

Introduction#

With two-factor login on, a correct password no longer signs the user in. It starts a pending login, kept in the session, and your app shows a page that asks for the code. Only the right code (or a recovery code) completes the login. This is Laravel Fortify's two-factor login, with an emailed code as well.

Each user has a method:

  • Email, the default: a code is mailed to the user when their password is accepted. It needs no setup, so every user has it from the start.
  • Authenticator app: the user scans a QR code with an app such as Google Authenticator or 1Password and confirms it with one code; from then on, the app's code is asked for.

The starter kits don't have two-factor pages yet: you add the routes and pages your app needs, as below.

Turning it on#

Add the four columns two-factor login keeps on users, then turn it on in config/auth.ts:

Terminal
node oriel two-factor:installnode oriel migrate
config/auth.ts
export default {  defaults: { guard: 'web', passwords: 'users' },  guards: { web: { driver: 'session', provider: 'users' } },  providers: { users: { driver: 'eloquent', model: User } },  two_factor: { enabled: true },}

two_factor takes these settings, each with its default:

SettingDefault
enabledfalseAsk for a second factor after the password
methods['email', 'app']The methods users may use (see below)
default'email'The method a user has until they set up another
code_ttl600Seconds an emailed code works
pending_ttl600Seconds a pending login waits for its code
max_attempts5Wrong codes a pending login allows; then the user signs in again
resend_after30Seconds before another email code may be sent
window1Authenticator steps (30 seconds each) of clock drift accepted either way
recovery_codes8How many recovery codes a user gets
issuerapp.nameThe name authenticator apps show

A user is asked only by a method open to them: email, or an app they have set up. With methods: ['app'], a user who hasn't set up an app has no method open, so their password alone signs them in, as in Fortify, where two-factor is each user's choice. Keep 'email' in methods to ask every user for a second factor.

The secret and the recovery codes are encrypted with your app key; emailed codes are kept hashed, in the cache, and so is the count of wrong codes, so the cache must be shared by your servers (database or redis, as on Vercel). With file or array on several servers, each one would count on its own.

Signing in#

Your login controller calls TwoFactor.attempt() instead of Auth.attempt(). It has three outcomes: 'authenticated' (the user is signed in: two-factor is off, or not asked of this user), 'challenge' (the password was right and the code is asked for), and false (wrong credentials):

app/Http/Controllers/LoginController.ts
import { back, redirect, request, TwoFactor } from '@orieljs/framework'import { Controller } from './Controller'export class LoginController extends Controller {  async authenticate() {    const credentials = await request().validate({ email: 'required|email', password: 'required' })    const result = await TwoFactor.attempt(credentials, request().boolean('remember'))    if (result === 'challenge') return redirect('/two-factor-challenge')    if (result === 'authenticated') {      await request().session().regenerate()      return redirect().intended('dashboard')    }    return back().withErrors({ email: 'The provided credentials do not match our records.' }).withInput(request().only('email'))  }}

The challenge page#

The challenge page's routes take the two-factor.challenge middleware: only a login waiting for its code reaches them, and anyone else is sent to log in.

routes/web.ts
import { back, redirect, request, Route, TwoFactor, view } from '@orieljs/framework'Route.middleware('two-factor.challenge').group(() => {  Route.get('/two-factor-challenge', async () => view('auth.two-factor', { challenge: await TwoFactor.challenge() }))  Route.post('/two-factor-challenge', async () => {    if (await TwoFactor.verify(String(request().input('code', '')))) {      await request().session().regenerate()      return redirect().intended('dashboard')    }    return back().withErrors({ code: 'That code is not right.' })  }).middleware('throttle:5,1')  Route.post('/two-factor-challenge/email', async () => {    await TwoFactor.useMethod('email')    return back()  })  Route.post('/two-factor-challenge/resend', async () => {    return back().with('status', (await TwoFactor.resend()) ? 'We sent you a new code.' : 'Wait a moment before asking again.')  })})

TwoFactor.challenge() gives the page what to say: the method asked for, the other methods the user has (methods), and where an emailed code went, masked (a***@example.com). verify() takes the 6-digit code for that method, or a recovery code, read leniently: spaces, dashes and capitals don't matter. A code works once; five wrong codes end the pending login, and the user signs in again.

The emailed code is the TwoFactorCode notification, sent with your mailer, so on Vercel your app needs a mail service over SMTP. TwoFactorCode.toMailUsing() lets you write the mail yourself:

app/Providers/AppServiceProvider.ts
TwoFactorCode.toMailUsing((_user, code, minutes) =>  new MailMessage().subject('Your sign-in code').line(`Your code is ${code}.`).line(`It works for ${minutes} minutes.`),)

Setting up an authenticator app#

On an account page, a signed-in user sets up their app in two steps: show the QR code, then confirm with a code from the app. Until it is confirmed, the app doesn't count, and the user is still asked by email:

routes/web.ts
Route.middleware('auth').group(() => {  Route.post('/account/two-factor/app', async () => {    const user = (await request().user<User>())!    // A form sent again after the app is set up: enableApp() would refuse.    if (TwoFactor.hasApp(user)) return back().with('status', 'Your app is set up already.')    const { svg, secret } = await TwoFactor.enableApp(user)    return view('account.two-factor-app', { svg, secret })  })  Route.post('/account/two-factor/app/confirm', async () => {    const confirmed = await TwoFactor.confirmApp((await request().user<User>())!, String(request().input('code', '')))    return confirmed ? back().with('status', 'Your app is set up.') : back().withErrors({ code: 'That code is not right.' })  })})

enableApp() returns the secret (for typing in by hand), its otpauth:// URL and the QR code as an SVG image. confirmApp() makes the app the user's method and gives them recovery codes. disableApp() removes it, and setMethod() lets a user who has both choose which is asked for.

TwoFactor.hasApp(user) says whether the user's app works, so a page can offer to set one up or to remove it. enableApp() on a working app throws TwoFactorAppAlreadyEnabledError, since a new secret would silently stop the old app's codes: call disableApp(user) first. Before the app is confirmed, calling enableApp() again just replaces the secret.

In a test, totpCode(secret, Date.now()) from @orieljs/framework gives the code the app would show.

Recovery codes#

TwoFactor.recoveryCodes(user) returns the user's codes, making them on first ask; show them once and ask the user to keep them somewhere safe. Each works once, in place of a code. regenerateRecoveryCodes(user) makes new ones, and the old ones stop working.

Choosing who is asked#

By default every user is asked for a second factor once two-factor is on. requireWhen() narrows it, for instance to admins:

app/Providers/AppServiceProvider.ts
TwoFactor.requireWhen((user) => (user as User).getAttribute('is_admin') === true)

Events#

TwoFactorChallenged (the code was asked for), TwoFactorFailed (a wrong code), TwoFactorAuthenticated (the user is signed in), RecoveryCodeUsed, TwoFactorAppEnabled and TwoFactorAppDisabled, each with the user. The password step fires Attempting and Failed, as Auth.attempt() does, and the login fires Login.

Was this page helpful?

Privacy policy ·

esc