keycloak-oidc-vite-express/server/middleware/ensureFreshToken.ts
2025-12-01 09:27:16 +01:00

32 lines
968 B
TypeScript

import { TokenSet } from "openid-client";
import type { Client } from "openid-client";
export function makeEnsureFreshToken(client: Client) {
return async function ensureFreshToken(req, res, next) {
if (!req.signedCookies?.tokenSet) {
return next(); // nessun token → passa oltre
}
const tokenSet = new TokenSet(req.signedCookies.tokenSet);
if (tokenSet.expired()) {
try {
const refreshed = await client.refresh(tokenSet.refresh_token);
// aggiorna il cookie firmato
res.cookie("tokenSet", refreshed, {
httpOnly: true,
signed: true,
sameSite: "lax",
secure: process.env.NODE_ENV === "production",
});
console.log("[OIDC] Access token rinnovato automaticamente");
} catch (err) {
console.error("[OIDC] Errore nel refresh:", err);
res.clearCookie("tokenSet");
return res.redirect("/login");
}
}
next();
};
}