Node.js Backend Example
This page is the same check as the Go example, for a Node.js backend. APP_SECTOR_ID is the app sector from the dashboard, not the organization Sector ID from signup. A token for another app in the same organization still returns HTTP 200.
A missing token, a non-200 introspect response, or the wrong sector is HTTP 401. A network or decode failure is HTTP 500. That failure is not a successful login.
exp and iat arrive as quoted strings. Convert them with Number before you compare them to a timestamp.
const express = require("express");
const app = express();const APP_SECTOR_ID = "your-app-sector-id";const INTROSPECT_URL = "https://api.spartanauth.com/api/v1/introspect";
// Returns null when SpartanAuth rejects the token.// Throws when the call fails or exp and iat are not numbers.async function introspectToken(token) { const resp = await fetch(INTROSPECT_URL, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ token }), }); if (resp.status !== 200) return null; const user = await resp.json(); const exp = Number(user.exp); const iat = Number(user.iat); if (!Number.isFinite(exp) || !Number.isFinite(iat)) { throw new Error("authentication error"); } user.exp = exp; user.iat = iat; return user;}
async function requireUser(req, res, next) { const header = req.get("Authorization") || ""; const token = header.startsWith("Bearer ") ? header.slice("Bearer ".length) : ""; if (!token) { res.status(401).send("missing token"); return; } let user; try { user = await introspectToken(token); } catch { res.status(500).send("authentication error"); return; } if (!user || user.sectorID !== APP_SECTOR_ID) { res.status(401).send("invalid token"); return; } req.user = user; next();}
app.get("/profile", requireUser, (req, res) => { res.json({ sub: req.user.sub });});fetch is built into Node.js 18 and later. The middleware uses Express’s req.get and next. On another framework, read the Authorization header the same way and stop the request with 401 or 500 before the route runs.