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.
Before you begin
Section titled “Before you begin”- Node.js 20 or later.
- A confidential client on your issuer with
client_secret_basic, the redirect URIhttp://localhost:3001/callback, the post-logout redirect URIhttp://localhost:3001/, and a minted secret. See Register a client.
Create the project
Section titled “Create the project”mkdir authwise-express && cd authwise-expressnpm init -ynpm pkg set type=module scripts.start="node server.js"npm install express openid-client cookie-sessionThis page was verified with Express 5.3, openid-client 6.8, and
cookie-session 2.1.
Write the server
Section titled “Write the server”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:
/logincreates the PKCE verifier,state, andnonce, keeps them in the session, and redirects to the issuer. The library discovered the endpoints at startup./callbackexchanges the code.authorizationCodeGrantchecksstateandnonceagainst the values you pass and validates the ID token. Itsclaims()are the ID token’s claims, andsubis the person’s stable ID./refreshexchanges the refresh token. The response carries a new refresh token and the old one is now refused, so the session always stores the newest./logoutclears the session and sends the browser to the issuer’s end-session endpoint, which ends the issuer session and returns to/.
Run it
Section titled “Run it”export AUTHWISE_ISSUER=https://login.example.comexport AUTHWISE_CLIENT_ID=CLIENT_IDexport AUTHWISE_CLIENT_SECRET="$(cat client-secret.txt)"npm startReplace 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.
Good to know
Section titled “Good to know”openid-client6 is a functional API over aConfiguration. The fourth argument todiscoveryis the client authentication: passclient.ClientSecretBasic(secret)for this client. A bare secret string selectsclient_secret_post, which the issuer also accepts.expectedStateandexpectedNonceleft 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. Computeexpires_atonce and store it. cookie-sessionkeeps 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_accessscope.
What’s next
Section titled “What’s next”- Send
access_tokenas 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.