Access Tokens, Refresh and Logout in a BFF
On this page
Swap the cookie for a token
On Day 2 the BFF forwarded /api/* to the tasks API unchanged. Now that sessions exist, the proxy has a real job: look up the session, find the access token, and send that to the API instead of the cookie.
await app.register(httpProxy, {
upstream: process.env.TASKS_API_URL!,
prefix: '/api',
preHandler: async (req, reply) => {
const session = await sessions.get(req.cookies['__Host-Http-sid'] ?? '');
if (!session) return reply.code(401).send({ error: 'not signed in' });
req.accessToken = await accessTokenFor(session);
},
replyOptions: {
rewriteRequestHeaders: (req, headers) => {
const { cookie, ...rest } = headers;
return { ...rest, authorization: `Bearer ${req.accessToken}` };
},
},
});req.accessToken needs a one-line type declaration (declare module 'fastify' { interface FastifyRequest { accessToken?: string } }).
Two things happen in rewriteRequestHeaders. The Authorization header is added, and the cookie header is removed. The tasks API has no business seeing the BFF's session cookie, and forwarding it would leak a credential to every downstream service. In the lab, the API saw:
{"sub":"ada","scope":["tasks:read","tasks:write"],"authHeaderPresent":true}
seenCookie: nullThe API checks the token
The downstream service doesn't trust the BFF blindly. It validates the token on every request: signature, issuer, expiry and audience. Here's the tasks API's check with the jose library:
import { createRemoteJWKSet, jwtVerify } from 'jose';
const JWKS = createRemoteJWKSet(new URL(`${ISSUER}/jwks`));
app.addHook('onRequest', async (req, reply) => {
const auth = req.headers.authorization;
if (!auth?.startsWith('Bearer ')) return reply.code(401).send({ error: 'missing token' });
try {
const { payload } = await jwtVerify(auth.slice(7), JWKS, {
issuer: ISSUER,
audience: 'https://api.taskboard.local',
});
req.user = { sub: payload.sub!, scope: String(payload.scope ?? '').split(' ') };
} catch {
return reply.code(401).send({ error: 'invalid token' });
}
});The audience check stops a token issued for some *other* API from being accepted here. If the BFF talks to several APIs with different audiences, it asks the identity provider for a token per API, using the resource parameter (RFC 8707) where the provider supports it.
Refresh before the token expires
Access tokens are short-lived, often 5 to 60 minutes. The refresh token from sign-in lets the BFF get a new one without bothering the user. Refresh a little *before* expiry, so a token never dies in the middle of a request:
async function accessTokenFor(session: SessionWithId): Promise<string> {
const t = session.data.tokens;
if (Date.now() < t.expiresAt - 30_000) return t.accessToken; // still good for 30 s+
const fresh = await oidc.refreshTokenGrant(config, t.refreshToken!);
session.data.tokens = {
accessToken: fresh.access_token,
refreshToken: fresh.refresh_token ?? t.refreshToken, // providers may rotate it
idToken: fresh.id_token ?? t.idToken,
expiresAt: Date.now() + (fresh.expiresIn() ?? 300) * 1000,
};
await sessions.update(session.id, session.data);
return fresh.access_token;
}Keep the new refresh token if the provider sends one. Many providers rotate refresh tokens: each use returns a new one and invalidates the old.
One refresh at a time
Rotation creates a race. The dashboard fires three API calls at once, all three see an expired token, and all three try to refresh. The first succeeds and rotates the refresh token. The other two present the *old* one, which the provider may treat as token theft and revoke the whole session.
The fix is a single flight: the first caller starts the refresh, and everyone else waits for the same promise.
const inFlight = new Map<string, Promise<string>>();
function accessTokenOnce(session: SessionWithId) {
let p = inFlight.get(session.id);
if (!p) {
p = accessTokenFor(session).finally(() => inFlight.delete(session.id));
inFlight.set(session.id, p);
}
return p;
}In the lab, after forcing the token to expire, two parallel API calls both returned 200, with exactly one refresh performed.
This map works inside one process. With several BFF instances, two of them can still race. Take a short Redis lock (SET refresh-lock:<id> 1 NX PX 5000) before refreshing, and have the loser re-read the session after a moment. Providers often allow a short grace period for the previous refresh token as well, which softens the problem.
When refreshing fails
If the refresh token has expired or been revoked, the user has to sign in again. Destroy the session and return 401. The React app should treat a 401 from any BFF call the same way: send the user to /auth/login?returnTo= plus the current path.
Sign out properly
Logging out of a BFF has two halves: end the BFF session, and end the session at the identity provider, or the next login click signs the user straight back in without asking.
app.post('/auth/logout', async (req, reply) => {
const id = req.cookies['__Host-Http-sid'];
const session = id ? await sessions.get(id) : null;
if (id) await sessions.destroy(id);
reply.clearCookie('__Host-Http-sid', { path: '/', httpOnly: true, secure: true, sameSite: 'lax' });
const redirectTo = session?.tokens.idToken
? oidc.buildEndSessionUrl(config, {
id_token_hint: session.tokens.idToken,
post_logout_redirect_uri: `${BASE}/`,
}).href
: '/';
return { redirectTo };
});Logout is a POST, not a GET, so a stray image tag on another site can't sign your users out. The app then sends the browser to redirectTo, the provider's end-session endpoint (RP-initiated logout), which ends the provider session and returns the user to the app. In the lab, after logout the session store was empty and the next API call returned 401.
If the provider supports token revocation (RFC 7009), revoke the refresh token too. That's what oidc.tokenRevocation(config, refreshToken) is for.
Check yourself
The session cookie is the BFF's own credential, and downstream services have no use for it. Forwarding it would hand every service, and every log it writes, a value that can impersonate the user against the BFF. The proxy sends only the access token, which is scoped to the service it's meant for.
All three try to refresh with the same token. The later ones present an already-rotated token, which can get the session revoked. A single-flight refresh makes them all wait for one refresh, plus a Redis lock across instances.
Destroying the BFF session alone leaves the user signed in at the identity provider. The next click on "Sign in" would log them straight back in without asking, which surprises users on shared computers. RP-initiated logout ends both sessions and returns the user to the app.
The audience check. Without verifying that the token's aud claim names this API, a token issued for some other service could be replayed here. Pass audience to jwtVerify, and have the BFF request a separate token per API when the provider supports resource indicators.
The refresh token has expired or been revoked, so the session can't continue. Destroy the BFF session and return 401, and let the app send the user to /auth/login with a returnTo. Retrying won't help.