Skip to content

Quickstart: Node.js with Express

This page gets an Express application signing people in through your issuer with openid-client: authorization code with PKCE, a cookie session, a refresh, and sign-out. It applies Sign users in with OpenID Connect and takes about ten minutes.

  • Node.js 20 or later.
  • A confidential client on your issuer with client_secret_basic, the redirect URI http://localhost:3001/callback, the post-logout redirect URI http://localhost:3001/, and a minted secret. See Register a client.
Terminal window
mkdir authwise-express && cd authwise-express
npm init -y
npm pkg set type=module scripts.start="node server.js"
npm install express openid-client cookie-session

This page was verified with Express 5.3, openid-client 6.8, and cookie-session 2.1.

Create server.js:

import express from 'express';
import cookieSession from 'cookie-session';
import * as client from 'openid-client';
import { randomBytes } from 'node:crypto';
const { AUTHWISE_ISSUER, AUTHWISE_CLIENT_ID, AUTHWISE_CLIENT_SECRET, PORT = 3001 } = process.env;
const redirect_uri = `http://localhost:${PORT}/callback`;
const post_logout_redirect_uri = `http://localhost:${PORT}/`;
// Discovery once at startup; the client authenticates with client_secret_basic.
const config = await client.discovery(
new URL(AUTHWISE_ISSUER), AUTHWISE_CLIENT_ID, undefined,
client.ClientSecretBasic(AUTHWISE_CLIENT_SECRET),
);
const app = express();
app.use(cookieSession({ name: 'session', secret: randomBytes(32).toString('hex'), httpOnly: true, sameSite: 'lax' }));
app.get('/', (req, res) => {
const { claims, expires_at } = req.session;
if (!claims) return res.send('<a href="/login">Sign in</a>');
res.send(`Signed in as ${claims.sub} (token expires ${new Date(expires_at).toISOString()})
<br><a href="/refresh">Refresh token</a> | <a href="/logout">Sign out</a>`);
});
app.get('/login', async (req, res) => {
const code_verifier = client.randomPKCECodeVerifier();
const state = client.randomState();
const nonce = client.randomNonce();
req.session.login = { code_verifier, state, nonce };
res.redirect(client.buildAuthorizationUrl(config, {
redirect_uri, scope: 'openid email profile offline_access', state, nonce,
code_challenge: await client.calculatePKCECodeChallenge(code_verifier), code_challenge_method: 'S256',
}).href);
});
app.get('/callback', async (req, res) => {
const { code_verifier, state, nonce } = req.session.login ?? {};
const tokens = await client.authorizationCodeGrant(config,
new URL(req.originalUrl, redirect_uri), { pkceCodeVerifier: code_verifier, expectedState: state, expectedNonce: nonce });
const { access_token, id_token, refresh_token } = tokens;
req.session = { claims: tokens.claims(), access_token, id_token, refresh_token, expires_at: Date.now() + tokens.expiresIn() * 1000 };
res.redirect('/');
});
app.get('/refresh', async (req, res) => {
const tokens = await client.refreshTokenGrant(config, req.session.refresh_token);
// Refresh tokens rotate: the old one is now refused, so keep the new one.
const { access_token, refresh_token } = tokens;
Object.assign(req.session, { access_token, refresh_token, expires_at: Date.now() + tokens.expiresIn() * 1000 });
res.send(`Refreshed; new expiry ${new Date(req.session.expires_at).toISOString()} <br><a href="/">Home</a>`);
});
app.get('/logout', (req, res) => {
const { id_token } = req.session;
req.session = null;
res.redirect(client.buildEndSessionUrl(config, { id_token_hint: id_token, post_logout_redirect_uri }).href);
});
app.listen(PORT, () => console.log(`http://localhost:${PORT}`));

What each route does:

  • /login creates the PKCE verifier, state, and nonce, keeps them in the session, and redirects to the issuer. The library discovered the endpoints at startup.
  • /callback exchanges the code. authorizationCodeGrant checks state and nonce against the values you pass and validates the ID token. Its claims() are the ID token’s claims, and sub is the person’s stable ID.
  • /refresh exchanges the refresh token. The response carries a new refresh token and the old one is now refused, so the session always stores the newest.
  • /logout clears the session and sends the browser to the issuer’s end-session endpoint, which ends the issuer session and returns to /.
Terminal window
export AUTHWISE_ISSUER=https://login.example.com
export AUTHWISE_CLIENT_ID=CLIENT_ID
export AUTHWISE_CLIENT_SECRET="$(cat client-secret.txt)"
npm start

Replace https://login.example.com with your issuer’s URL and CLIENT_ID with the client’s ID. Open http://localhost:3001/, click Sign in, and sign in on the hosted page. The home page shows Signed in as u-… with the token’s expiry. Refresh token shows a later expiry, and Sign out returns you to the sign-in link.

  • openid-client 6 is a functional API over a Configuration. The fourth argument to discovery is the client authentication: pass client.ClientSecretBasic(secret) for this client. A bare secret string selects client_secret_post, which the issuer also accepts.
  • expectedState and expectedNonce left undefined mean “expect none”, and the exchange then fails when the issuer returns them. Always pass what you stored.
  • The library gives you expiresIn(), not an absolute expiry. Compute expires_at once and store it.
  • cookie-session keeps everything in a signed cookie with a 4 KB limit. The three tokens plus the claims fit with room to spare, but a server-side store is the better home for a real application.
  • A refresh token comes only with the offline_access scope.
  • Send access_token as a bearer token to the API the client’s audience names, and validate it there against the issuer’s JWKS.
  • Read Keep the session alive for the refresh token lifetimes and how to tune them.