Skip to content

Authentication ​

Introduction ​

Authentication answers one question: who is making this request? @plinthjs/auth answers it with three small pieces. A user is any object that can report an identifier and a password hash. A user provider knows how to find users in storage and check their credentials. A guard uses a provider to work out who the current user is, either from the session (browsers) or from a token (APIs).

The package also ships the HTTP middleware that protects routes, a session guard with remember-me, HTTP Basic, logout-everywhere support, password re-confirmation, a set of events, and an AuthManager for registering your own guards.

bash
pnpm add @plinthjs/auth @plinthjs/session @plinthjs/encryption

INFO

The examples on this page build on the session middleware from Session and the password hasher from Hashing. If you want ready-made registration, login, and two-factor actions on top of this package, see Accounts.

Users and providers ​

A user is anything that implements Authenticatable: getAuthIdentifier(), getAuthIdentifierName(), and getAuthPassword() (the stored hash). GenericUser wraps a plain record and also supports remember tokens and password updates, which is enough for most applications.

A provider implements UserProvider. ArrayUserProvider keeps a list of users in memory (GenericUser objects, or any Authenticatable, such as the AccountUser from @plinthjs/accounts) and verifies passwords with a Hasher. It is ideal for tests and prototypes:

ts
import { Hasher } from '@plinthjs/encryption'
import { ArrayUserProvider, GenericUser } from '@plinthjs/auth'

const hasher = new Hasher()

const provider = new ArrayUserProvider(
  [
    new GenericUser({
      id: 1,
      name: 'Ada',
      email: 'ada@example.com',
      password: hasher.make('secret'),
    }),
  ],
  hasher,
)

const user = await provider.retrieveByCredentials({ email: 'ada@example.com' })
user?.getAuthIdentifier() // => 1

retrieveByCredentials ignores any key that contains password and matches the remaining keys exactly against the user's attributes. That is why you pass { email, password } to a guard and the provider only looks the user up by email.

Writing a database provider ​

For a real application you implement UserProvider against your own storage. The generated application does exactly this with the query builder (src/auth/database-user-provider.ts). The contract has five required methods:

ts
import { GenericUser } from '@plinthjs/auth'
import type { Authenticatable, Credentials, UserProvider } from '@plinthjs/auth'
import type { Connection } from '@plinthjs/database'
import type { Hasher } from '@plinthjs/encryption'

export class DatabaseUserProvider implements UserProvider {
  private readonly db: Connection
  private readonly hasher: Hasher

  constructor(db: Connection, hasher: Hasher) {
    this.db = db
    this.hasher = hasher
  }

  async retrieveById(id: string | number): Promise<Authenticatable | null> {
    const row = await this.db.table('users').where('id', id).first()
    return row === null ? null : new GenericUser(row)
  }

  async retrieveByToken(id: string | number, token: string): Promise<Authenticatable | null> {
    const row = await this.db.table('users').where('id', id).where('remember_token', token).first()
    return row === null ? null : new GenericUser(row)
  }

  async updateRememberToken(user: Authenticatable, token: string): Promise<void> {
    await this.db
      .table('users')
      .where('id', user.getAuthIdentifier())
      .update({ remember_token: token })
  }

  async retrieveByCredentials(credentials: Credentials): Promise<Authenticatable | null> {
    const email = credentials['email']
    if (typeof email !== 'string') return null
    const row = await this.db.table('users').where('email', email).first()
    return row === null ? null : new GenericUser(row)
  }

  async validateCredentials(user: Authenticatable, credentials: Credentials): Promise<boolean> {
    const password = credentials['password']
    return typeof password === 'string' && this.hasher.check(password, user.getAuthPassword())
  }
}

WARNING

The provider that ships in the generated app compares remember tokens with timingSafeEqual. If you compare tokens yourself, do it in constant time, as ArrayUserProvider does. A plain where('remember_token', token) query is fine for a database that indexes the column, but never compare secrets with === in application code.

The session guard ​

SessionGuard stores the authenticated user's id in the session and loads the user from the provider on demand. Build one per request from a provider and the request's session:

ts
import { SessionGuard } from '@plinthjs/auth'
import { session } from '@plinthjs/session'

import type { Request } from '@plinthjs/http'

function auth(request: Request): SessionGuard {
  return new SessionGuard(provider, session(request))
}

session(request) is the helper from @plinthjs/session that returns the request's session (and throws a clear error when the startSession middleware did not run). The guard caches the resolved user for its own lifetime, so calling user() several times in one request costs one provider lookup.

Attempting a login ​

attempt() finds the user by the non-password credentials, verifies the password, and on success stores the user in the session:

ts
import { Response } from '@plinthjs/http'

router.post('/login', async (request) => {
  const guard = auth(request)

  const ok = await guard.attempt({
    email: request.string('email'),
    password: request.string('password'),
  })

  if (!ok) return Response.json({ message: 'These credentials do not match.' }, 422)

  return Response.redirectTo('/dashboard')
})

A successful attempt(), login(), loginUsingId() or loginUsingRecaller() rotates the session id (the bag is kept and a new CSRF token is minted), which defeats session fixation, and the startSession middleware removes the old id's entry from the store. You do not need to call regenerate() yourself. The SessionGuardOptions.regenerateSession option replaces this with your own function, or turns it off with false (not recommended).

Other ways to authenticate:

ts
await guard.validate({ email, password }) // check credentials without logging in
await guard.once({ email, password }) // authenticate for this request only, no session
guard.login(user) // log in a user object you already have
await guard.loginUsingId(1) // log in by id, resolves to the user or null
guard.setUser(user) // set the user on this guard instance without touching the session

once() is useful for stateless endpoints that still want to reuse the credential check. loginUsingId() is what you call right after registering a user.

Extra login conditions ​

attemptWhen() runs callbacks after the credentials validate. Every callback must return true, otherwise the attempt fails and the user is not logged in. The callbacks receive the user and the guard, and may be async:

ts
import type { GenericUser } from '@plinthjs/auth'

const ok = await guard.attemptWhen({ email, password }, (user) => {
  return (user as GenericUser).getAttribute('active') === true
})

// Several conditions
await guard.attemptWhen({ email, password }, [isActive, hasVerifiedEmail])

After any attempt, guard.getLastAttempted() returns the user the credentials resolved to, or null when the email matched nobody. That lets you tell "unknown account" from "wrong password" in your own logging.

Rehashing passwords ​

When a login succeeds, the guard calls the provider's optional rehashPasswordIfRequired(user, credentials). ArrayUserProvider implements it: if the stored hash was made with different cost parameters than the provider's Hasher, it hashes the plaintext password again and stores the new hash through setAuthPassword(). This is how you raise the scrypt cost over time without forcing a password reset:

ts
import { Session } from '@plinthjs/session'

const oldHasher = new Hasher({ cost: 1024 })
const user = new GenericUser({ id: 1, email: 'a@b.c', password: oldHasher.make('secret') })
const provider = new ArrayUserProvider([user], new Hasher())

const guard = new SessionGuard(provider, new Session('demo', {}))
await guard.attempt({ email: 'a@b.c', password: 'secret' })
new Hasher().needsRehash(user.getAuthPassword()) // => false (upgraded during the login)

If you write your own provider, implement rehashPasswordIfRequired and persist the new hash yourself. Providers that omit it simply skip the step.

Remember me ​

"Remember me" keeps a user signed in after the session expires. The guard does not write cookies itself. It hands you a recaller value (id|token) to store in a long-lived cookie, and it can log a user in from that value later.

ts
router.post('/login', async (request) => {
  const guard = auth(request)
  const ok = await guard.attempt(
    {
      email: request.string('email'),
      password: request.string('password'),
    },
    request.boolean('remember'), // the second argument is the remember flag
  )
  if (!ok) return Response.json({ message: 'Bad credentials.' }, 422)

  const response = Response.redirectTo('/dashboard')

  const recaller = guard.pullRecaller()
  if (recaller !== null) {
    response.cookie('remember_web', recaller, {
      maxAge: guard.getRememberDuration() * 60, // the duration is in minutes
      httpOnly: true,
      sameSite: 'Lax',
    })
  }
  return response
})

attempt(credentials, true) issues the remember token as part of the login and holds the recaller until you read it once with pullRecaller() (it returns null when no remembered login just happened). To issue one for an already logged-in user, call remember(user) instead. It generates a random token, saves it through the provider's updateRememberToken(), and returns the recaller. The default lifetime is 576000 minutes (400 days); change it with guard.setRememberDuration(minutes).

To honour the cookie, add a middleware that runs after startSession and logs the user in when the session is empty:

ts
import type { Middleware } from '@plinthjs/http'

const rememberMe: Middleware = async (request, next) => {
  const guard = auth(request)
  const recaller = request.cookie('remember_web')

  if (!(await guard.check()) && recaller !== undefined) {
    await guard.loginUsingRecaller(recaller)
  }
  return next(request)
}

loginUsingRecaller() verifies the token in constant time, logs the user into the session, and returns the user (or null for a malformed or stale value). guard.viaRemember() is true afterwards, which lets you ask for the password again before sensitive actions when the user did not log in interactively.

Logging out ​

There are three ways to log out, with different effects on remembered devices.

ts
router.post('/logout', async (request) => {
  await auth(request).logout()
  session(request).invalidate()
  return Response.redirectTo('/').cookie('remember_web', '', { maxAge: 0 })
})
MethodSession clearedRemember tokenEvent dispatched
logout()yescycled, so every device diesLogout
logoutCurrentDevice()yeskept, other devices stay inCurrentDeviceLogout
logoutOtherDevices(pwd)no (this one)cycled, a new recaller is returnedOtherDeviceLogout

logout() clears the session keys synchronously and then cycles the remember token, so await it. logoutCurrentDevice() leaves the token alone.

Logging out other devices ​

logoutOtherDevices() is for "sign out everywhere else" after a password change. It checks the given password against the current user (throwing Error('The given password does not match the current password.') if it is wrong), force-rehashes the password, refreshes this session's stored password hash, and cycles the remember token. It resolves to the fresh recaller for this device:

ts
router
  .post('/settings/logout-others', async (request) => {
    const guard = auth(request)
    const recaller = await guard.logoutOtherDevices(request.string('password'))

    const response = Response.json({ ok: true })
    if (recaller !== null) {
      response.cookie('remember_web', recaller, { httpOnly: true, maxAge: 34_560_000 })
    }
    return response
  })
  .middleware(authenticateSession(provider))

Other sessions are invalidated by the authenticateSession middleware (next section). Each request, it compares the password hash stored in the session with the user's current hash. After logoutOtherDevices() the hash changed, so every other session fails the comparison and receives a 401. Without authenticateSession on your routes, other sessions keep working.

Protecting routes ​

@plinthjs/auth ships middleware for the common cases. They attach the user to the request, which you read with getUser(request).

ts
import { authenticateSession, getUser, redirectIfAuthenticated } from '@plinthjs/auth'
import { startSession } from '@plinthjs/session'

router
  .get('/dashboard', (request) => {
    const user = getUser(request)
    return Response.json({ id: user?.getAuthIdentifier() })
  })
  .middleware(authenticateSession(provider))

router.get('/login', showLogin).middleware(redirectIfAuthenticated(provider, '/dashboard'))

authenticateSession(provider) requires startSession to have run first (otherwise it throws a 500 explaining so). It resolves the user from the session, attaches it, and throws AuthenticationError (a 401) when nobody is signed in. It also enforces the password-hash check described above.

redirectIfAuthenticated(provider, redirectTo = '/home') is the guest-only middleware for login and registration pages: signed-in users are redirected, guests (and requests with no session) pass through.

authenticateToken(provider, inputKey?) does the same for stateless API requests using a token. It reads the token from the Authorization: Bearer header, then the api_token query string, then the api_token input field, and asks the provider for a user matching { api_token: token }:

ts
import { authenticateToken } from '@plinthjs/auth'

router
  .get('/api/me', (request) => Response.json({ id: getUser(request)?.getAuthIdentifier() }))
  .middleware(authenticateToken(provider))

For a request with no valid token, JSON clients receive {"message":"Unauthenticated.","status":401}. See Errors for how thrown errors become responses, and API Tokens for personal access tokens with abilities and expiry.

Redirecting browsers instead of returning 401 ​

AuthenticationError renders as a 401, which suits APIs. For browser pages you usually want a redirect to the login page. Write a small middleware of your own, as the generated application does:

ts
import { getSession } from '@plinthjs/session'
import { SessionGuard } from '@plinthjs/auth'
import type { Middleware } from '@plinthjs/http'

export const authenticate = (): Middleware => async (request, next) => {
  const session = getSession(request)
  const signedIn = session !== undefined && (await new SessionGuard(provider, session).check())
  return signedIn ? next(request) : Response.redirectTo('/login')
}

You can register middleware under a name with router.aliasMiddleware('auth', authenticateSession(provider)) and use it as .middleware('auth'). See Middleware.

Retrieving the authenticated user ​

Inside a handler behind authenticateSession or authenticateToken, use getUser(request). It returns the Authenticatable the middleware attached, or undefined:

ts
import { getUser } from '@plinthjs/auth'

const user = getUser(request)
user?.getAuthIdentifier()

Anywhere else, ask a guard:

ts
const guard = auth(request)

await guard.check() // => true when someone is signed in
await guard.guest() // => true when nobody is
await guard.user() // => the user, or null
await guard.id() // => the user's identifier, or null

Because Authenticatable only exposes the identifier and password, a GenericUser gives you the full record through user.attributes or getAttribute('name'). If your application uses its own user class, cast to it after retrieving:

ts
const user = (await guard.user()) as GenericUser | null
user?.getAttribute('email') // => 'ada@example.com'

Confirming the password ​

Sensitive pages (deleting an account, changing billing details) can require a recent password confirmation. requirePassword() is a middleware that passes when the session holds a confirmation timestamp younger than the timeout, and otherwise redirects to the confirmation page. JSON clients receive a 423 Locked response with {"message":"Password confirmation required."}.

ts
import { authenticateSession, confirmPassword, getUser, requirePassword } from '@plinthjs/auth'

router
  .get('/settings/danger', showDangerZone)
  .middleware(authenticateSession(provider), requirePassword('/confirm-password', 10_800))

router
  .post('/confirm-password', async (request) => {
    const ok = await confirmPassword(
      provider,
      session(request),
      getUser(request)!,
      request.string('password'),
    )
    return ok
      ? Response.redirectTo('/settings/danger')
      : Response.json({ message: 'Wrong password.' }, 422)
  })
  .middleware(authenticateSession(provider))

The first argument is the redirect target (default /confirm-password) and the second is the timeout in seconds (default 10800, three hours). confirmPassword() validates the password and stamps auth.password_confirmed_at in the session; it returns false and leaves the session untouched when the password is wrong. The password-confirmation action in Accounts does the same check without the session step.

HTTP Basic authentication ​

For quick internal tools, a session guard can authenticate from an Authorization: Basic header. Give the guard the request through the options or setRequest():

ts
const guard = new SessionGuard(provider, session(request), undefined, { request })

const challenge = await guard.basic() // uses the "email" field by default
if (challenge !== undefined) return challenge // a 401 with WWW-Authenticate: Basic

basic() resolves to undefined when the user is already signed in or the header validates (and logs the user into the session). Otherwise it resolves to a ready-made 401 response with WWW-Authenticate: Basic. onceBasic() does the same without persisting anything to the session, which is the right choice for stateless endpoints. Pass a different field name, for example guard.basic('username'), when your credentials are not keyed by email.

Token guard ​

TokenGuard authenticates each request from a token with no server-side session. It takes a provider and the request, and looks the token up through provider.retrieveByCredentials({ api_token: token }):

ts
import { TokenGuard } from '@plinthjs/auth'

const guard = new TokenGuard(provider, request) // reads Bearer header, ?api_token=, or api_token input
const user = await guard.user()

new TokenGuard(provider, request, 'token') // read a different query/input key

With ArrayUserProvider, the lookup matches a user whose api_token attribute equals the presented token. Applications that need hashed, expiring, ability-scoped tokens should use API Tokens instead.

Named guards with the AuthManager ​

AuthManager is a registry of guard factories, so code can ask for "the api guard" without knowing how it is built. Register factories with extend() and resolve them with guard():

ts
import { AuthManager, SessionGuard, TokenGuard } from '@plinthjs/auth'

const auth = new AuthManager('web') // the default guard name is 'web'

auth.extend(
  'web',
  (request) => new SessionGuard(provider, session(request!), undefined, { request }),
)
auth.extend('api', (request) => new TokenGuard(provider, request!))

const guard = auth.guard('api', request)
const same = auth.guard(undefined, request) // falls back to the default guard

guard(name, request) passes the request to the factory, so request-scoped guards can be built fresh every time. Asking for a guard that was not registered throws Auth guard [name] is not defined. Use setDefaultGuard() and getDefaultGuard() to change or read the default.

Closure-based guards ​

viaRequest() registers a guard that delegates to a callback. The callback receives the request (and the provider if you passed one) and returns a user or null. It is the quickest way to support a custom scheme, such as a signed header from a gateway:

ts
auth.viaRequest(
  'gateway',
  async (request, users) => {
    const id = request.header('x-user-id')
    return id === undefined ? null : (users?.retrieveById(Number(id)) ?? null)
  },
  provider,
)

const guard = auth.guard('gateway', request)
await guard.check() // => true when the header names a known user

The guard it builds is a RequestGuard. It resolves the user once, caches it, and exposes the read-only Guard interface (check, guest, user, id, validate, setUser). setRequest(request) swaps the request and clears the cached user.

Writing a custom guard ​

A guard is any object that implements Guard (read-only) or StatefulGuard (adds attempt, once, login, loginUsingId, and logout). Implement the interface and register it with extend():

ts
import type { Authenticatable, Credentials, Guard } from '@plinthjs/auth'
import type { Request } from '@plinthjs/http'

class ApiKeyGuard implements Guard {
  private current: Authenticatable | null = null
  private loaded = false

  constructor(
    private readonly keys: Map<string, Authenticatable>,
    private readonly request: Request,
  ) {}

  async user(): Promise<Authenticatable | null> {
    if (!this.loaded) {
      this.current = this.keys.get(this.request.header('x-api-key') ?? '') ?? null
      this.loaded = true
    }
    return this.current
  }
  async check(): Promise<boolean> {
    return (await this.user()) !== null
  }
  async guest(): Promise<boolean> {
    return !(await this.check())
  }
  async id(): Promise<string | number | null> {
    return (await this.user())?.getAuthIdentifier() ?? null
  }
  async validate(credentials: Credentials): Promise<boolean> {
    return this.keys.has(String(credentials['key']))
  }
  setUser(user: Authenticatable): void {
    this.current = user
    this.loaded = true
  }
}

auth.extend('apikey', (request) => new ApiKeyGuard(keys, request!))

Authentication events ​

Guards and the password broker can dispatch events for logging, auditing, and notifications. They dispatch through a minimal seam, AuthEvents, which is any object with a dispatch(event: object) method. When you pass no dispatcher, nothing is dispatched and there is no overhead.

ts
import { Dispatcher } from '@plinthjs/events'
import { Login, SessionGuard } from '@plinthjs/auth'

const dispatcher = new Dispatcher()

dispatcher.listen(Login, (login) => {
  console.log(`${login.guard}: user ${login.user.getAuthIdentifier()} signed in`)
})

const guard = new SessionGuard(provider, session, undefined, { name: 'web', events: dispatcher })

The Dispatcher from Events accepts event classes and instances directly, so it can be passed as events with no adapter. The guard options also accept name, which is carried on every event as guard.

EventFired when
Attemptingbefore a credential attempt (carries the plaintext credentials)
Validatedcredentials check out against a user
Logina user is logged into the session (remember is true for a recaller)
Authenticateda user is set on a guard, including setUser() and token guards
Failedan attempt fails (user is null when no account matched)
Logoutlogout() completes
CurrentDeviceLogoutlogoutCurrentDevice() completes
OtherDeviceLogoutlogoutOtherDevices() completes
PasswordResetPasswordBroker.reset() succeeds
VerifiedEmailVerifier.verify() marks an address verified
Registered, Lockoutclasses you dispatch yourself from registration and throttling code

A successful attempt() dispatches Attempting, Validated, Login, Authenticated in that order. A failed one dispatches Attempting then Failed.

WARNING

Attempting and Failed carry the plaintext password inside credentials. Do not log them wholesale.

Testing ​

Everything on this page runs in memory. Build an ArrayUserProvider, a Session (or the startSession middleware with ArraySessionStore), and a kernel, then send fake requests:

ts
import { HttpKernel, Request, Router } from '@plinthjs/http'
import { ArraySessionStore, SessionManager, startSession } from '@plinthjs/session'

const kernel = new HttpKernel(router, {
  middleware: [startSession(new SessionManager(new ArraySessionStore()))],
})

const response = await kernel.handle(new Request({ method: 'GET', url: '/dashboard' }))
response.status // => 401

To exercise a signed-in request, log in through your login route first and pass the returned plinth_session cookie on the next request. A Hasher created with a small cost, such as new Hasher({ cost: 1024 }), keeps tests fast.

Released under the MIT License.