Skip to content

triauth for Express

A complete sign-in flow for an Express app in about 40 lines, with express-session holding the challenge.

Library
triauth-js
Requires
Node.js 18 or newer
Install
npm install triauth express express-session

Intro

The official triauth-js open-source library can be used with Express based web applications.

Sign-in is two simple calls to the library, with no passwords to store, protect, or reset.

Integrate triauth with your application in an afternoon and boost your metrics by offering a simple, effortless way for users to sign in and try it. Once you do, make sure to let us know - we love featuring integrations on the triauth project's website.

Get started

This guide shows you how to add "Sign in with triauth" to an Express app with triauth-js and express-session. At the end you have an app with a sign-in form that sends the user to their authenticator and signs them in when they approve. It takes about fifteen minutes.

How sign-in works

A sign-in has three stages, and your app calls Triauth.authenticate twice:

javascript
// 1. request: start a sign-in for the identifier the user typed
const { challenge, redirectUrl } = await Triauth.authenticate({ identifier, callbackUrl });

// 2. redirect: keep the challenge on the server, send the user to their authenticator
req.session.challenge = challenge;
res.redirect(redirectUrl);

// 3. verify: the browser comes back to callbackUrl with a response
const result = await Triauth.authenticate({ challenge: req.session.challenge, response });
delete req.session.challenge; // a challenge is good for one attempt only
if (result.authenticated) req.session.identifier = result.identifier;

We will follow these stages in this tutorial, and start by building a sign-in page, then follow the request through the authenticator, and finally verify the received response. See the sign-in flow guide for more details.

Before you start

  • Node.js 18 or newer. Check with node --version.
  • A triauth identity of your own, set up in the browser you test with. See Set up your identity.
  • An empty folder, or an existing Express project.

1. Install the packages ​

Add triauth-js, Express, and express-session, which keeps the challenge on the server between the two calls.

shell
npm install triauth express express-session

2. Create the sign-in page ​

Create app.mjs. It serves a sign-in form at /, and the form posts the identifier to /login, where stages 1 and 2 run.

javascript
import * as Triauth from 'triauth';
import express from 'express';
import session from 'express-session';
import { randomBytes } from 'node:crypto';

// the address the authenticator sends the browser back to, never built from request headers
const callbackUrl = 'http://localhost:3000/callback'; // your public address in production

const app = express();
app.use(express.urlencoded());
// sessions in memory with a new secret on every start, so a restart signs everyone out
app.use(session({ secret: randomBytes(32).toString('hex'), resave: false, saveUninitialized: false }));

// the home page: the identifier when signed in, the sign-in form otherwise
app.get('/', (req, res) => {
  if (req.session.identifier) return res.send(`Signed in as ${req.session.identifier}`);
  const error = req.session.error?.message ?? '';
  delete req.session.error;
  res.send(`
    <form action="/login" method="post">
      <input name="identifier" placeholder="you@example.com">
      <button>Sign in with triauth</button>
      <p style="color: red">${error}</p>
    </form>`);
});

// the sign-in form posts here
app.post('/login', async (req, res) => {
  // make sure the sign-in is from this site's own pages
  const site = req.get('sec-fetch-site');
  if (site && site !== 'same-origin') return res.sendStatus(403);
  const identifier = req.body?.identifier ?? '';

  // 1. request
  const result = await Triauth.authenticate({ identifier, callbackUrl });

  // 2. redirect, when the result holds a challenge
  if (result.challenge) {
    req.session.challenge = result.challenge; // kept on the server, where the user cannot change it
    return res.redirect(result.redirectUrl);
  }
  req.session.error = result.error; // an invalid identifier, or a domain that is not set up for triauth
  res.redirect('/');
});

app.listen(3000, () => console.log('Listening on http://localhost:3000'));

The /login route runs stages 1 and 2. Triauth.authenticate reads the DNS records of the identifier's domain, finds the user's authentication endpoint there, and returns a challenge and a redirectUrl. If the identifier is malformed, or its domain is not set up for triauth, it returns an error instead, and the form shows its message. The challenge goes into the session, and the browser is redirected to the authenticator.

A few parts of this file matter for your own app too.

The session keeps the challenge between the two calls, where the user cannot change it. express-session keeps its sessions in memory with a new secret on every start, which is enough for a tutorial. In your app, give it a fixed secret from your configuration and a persistent store. Its cookie is SameSite=Lax by default, so the browser sends it when the authenticator brings the user back to your site.

The sec-fetch-site check refuses a sign-in form that another website posted. Without it, another website could post an attacker's identifier to /login from the user's browser, and your app would sign the user in to the attacker's account. Browsers set this header to same-origin for a form from your own pages. A CSRF token does the same job. See Stage 1 of the sign-in flow.

callbackUrl is fixed configuration. Do not build it from the Host header of the request, which the client controls.

The redirect to the authenticator must keep the Referer header, which the authenticator compares with your callback URL. The browser's default policy sends your origin, so this works unless your app sets a no-referrer policy. Helmet does, see Troubleshooting below.

Start the app:

shell
node app.mjs

Open http://localhost:3000 in the browser where your identity is set up, and enter your identifier.

Checkpoint

You should see the form, then your authenticator asking you to approve a sign-in to http://localhost:3000/.

3. Approve the request ​

The browser is now at the user's authenticator, with the challenge in the URL. The authenticator shows the address of your website and the identifier, and asks the user to approve or deny.

Click Approve.

Checkpoint

The browser lands on http://localhost:3000/callback?response= followed by the encrypted response, and the page says "Cannot GET /callback". The app has no route for /callback yet. The next step adds it.

4. Receive the response and sign the user in ​

In app.mjs, add the callback route between the /login route and app.listen.

javascript
// the sign-in form posts here
app.post('/login', async (req, res) => {
  // ...
});

// 3. verify: the authenticator sends the browser back here, with the response in the query string
app.get('/callback', async (req, res) => { 
  const response = req.query.response ?? ''; 
  const result = await Triauth.authenticate({ challenge: req.session.challenge ?? '', response }); 
  delete req.session.challenge; // a challenge is good for one attempt only
  if (result.authenticated) req.session.identifier = result.identifier; 
  else req.session.error = result.error; // denied, expired, or not verified
  res.redirect('/'); // always redirect, so that the response does not stay in the address bar
}); 

app.listen(3000, () => console.log('Listening on http://localhost:3000'));

This route runs the response verification stage. It reads response from the query string and passes it to Triauth.authenticate together with the challenge from the session. The library decrypts the response with the key in the challenge, reads the identity records again, and checks the signature against the public keys published there. On success, result.authenticated is true and result.identifier is the verified identifier, which the route stores in the session. On failure, result.error says why, with a code such as request_denied or request_expired.

The challenge is deleted from the session before the result is read, so that one challenge serves one attempt. The route always ends with a redirect to /, where the home page shows the signed-in state, and the response does not stay in the address bar. Receiving the response explains how the response reaches /callback and what it leaves in your logs.

The result has more fields than the identifier, such as the name of the device that signed and a session key for the requests that follow. Read Stage 3 of the sign-in flow for the full list and what to store.

Stop the app with Ctrl+C, start it again, and sign in once more:

shell
node app.mjs

Checkpoint

After you approve, you should see the page "Signed in as" followed by your identifier. If you deny the request, the form comes back with "Request has been denied" in red.

5. Celebrate 🎉 ​

You now have a fully functional "Sign in with triauth" flow. But don't stop yet - there is so much more you can do with triauth! You can periodically validate sessions with Triauth.check and Triauth.ping, ask for terms acceptance with Triauth.sign, and verify that the user is not a robot with Triauth.attest. See the triauth-js README to learn more, or visit the triauth playground.

The complete app.mjs
javascript
import * as Triauth from 'triauth';
import express from 'express';
import session from 'express-session';
import { randomBytes } from 'node:crypto';

// the address the authenticator sends the browser back to, never built from request headers
const callbackUrl = 'http://localhost:3000/callback'; // your public address in production

const app = express();
app.use(express.urlencoded());
// sessions in memory with a new secret on every start, so a restart signs everyone out
app.use(session({ secret: randomBytes(32).toString('hex'), resave: false, saveUninitialized: false }));

// the home page: the identifier when signed in, the sign-in form otherwise
app.get('/', (req, res) => {
  if (req.session.identifier) return res.send(`Signed in as ${req.session.identifier}`);
  const error = req.session.error?.message ?? '';
  delete req.session.error;
  res.send(`
    <form action="/login" method="post">
      <input name="identifier" placeholder="you@example.com">
      <button>Sign in with triauth</button>
      <p style="color: red">${error}</p>
    </form>`);
});

// the sign-in form posts here
app.post('/login', async (req, res) => {
  // make sure the sign-in is from this site's own pages
  const site = req.get('sec-fetch-site');
  if (site && site !== 'same-origin') return res.sendStatus(403);
  const identifier = req.body?.identifier ?? '';

  // 1. request
  const result = await Triauth.authenticate({ identifier, callbackUrl });

  // 2. redirect, when the result holds a challenge
  if (result.challenge) {
    req.session.challenge = result.challenge; // kept on the server, where the user cannot change it
    return res.redirect(result.redirectUrl);
  }
  req.session.error = result.error; // an invalid identifier, or a domain that is not set up for triauth
  res.redirect('/');
});

// 3. verify: the authenticator sends the browser back here, with the response in the query string
app.get('/callback', async (req, res) => {
  const response = req.query.response ?? '';
  const result = await Triauth.authenticate({ challenge: req.session.challenge ?? '', response });
  delete req.session.challenge; // a challenge is good for one attempt only
  if (result.authenticated) req.session.identifier = result.identifier;
  else req.session.error = result.error; // denied, expired, or not verified
  res.redirect('/'); // always redirect, so that the response does not stay in the address bar
});

app.listen(3000, () => console.log('Listening on http://localhost:3000'));
CommonJS

If your project uses require, save the app as app.cjs and replace the four import lines with these:

javascript
const Triauth = require('triauth');
const express = require('express');
const session = require('express-session');
const { randomBytes } = require('node:crypto');

Troubleshooting

Nothing happens when you submit the form ​

If your app uses Helmet, its default Content Security Policy has form-action 'self', so the browser blocks the redirect from /login to the authenticator and reports a form-action violation in the console. Add https: to form-action, because every user's authenticator has its own address.

The authenticator says it could not determine the referring website address ​

Helmet also sets Referrer-Policy: no-referrer by default, which removes the Referer header that the authenticator checks. Set the browser's default policy, strict-origin-when-cross-origin, which sends only your origin.

Both changes together:

javascript
app.use(helmet({
  contentSecurityPolicy: { directives: { formAction: ["'self'", 'https:'] } },
  referrerPolicy: { policy: 'strict-origin-when-cross-origin' }
}));

Next steps

  • Read The sign-in flow for what the result object contains and what to store from it.
  • Read Sessions and sign-out to confirm during the session that the device is still trusted, with Triauth.check and Triauth.ping.
  • Read Configuration for the DNS resolvers, the DNSSEC flag, and caching on a busy server.
  • See triauth for Node.js for the same sign-in on a plain Node.js server, with no framework.
  • The triauth-js README has the full API, including Triauth.whois to look up an identity, signatures, stamps, and attestations.
  • The Playground lets you try the protocol in your browser before you write code.

All logos and trademarks belong to their respective owners and do not imply affiliation or endorsement of the organization or product by triauth, nor vice versa. The content provided on this page may include information from third-party sources. We do not assume any responsibility for the completeness, correctness, or applicability of the information. You should independently verify any details before relying on them.