Sign in

Introspect Access Tokens

This guide shows how to configure token introspection for a Fastify API using the MonoCloud Backend Node SDK.

With introspection, tokens are validated by sending them to the authorization server's introspection endpoint instead of being validated locally. This is required for opaque tokens and can also be enabled for JWT tokens.

When to use introspection

Use introspection when:

  • Your API receives opaque access tokens
  • You want to receive token claims and check revocation status
  • You want all tokens validated server-side

Before you begin

This guide assumes you've completed the installation guide.

You should already have:

  • A Fastify project
  • The @monocloud/backend-node SDK installed
  • Environment variables configured in .env

Configure environment variables

Add the client credentials and introspection setting to your .env file:

.env
MONOCLOUD_BACKEND_TENANT_DOMAIN=https://<your-domain>
MONOCLOUD_BACKEND_AUDIENCE=https://<your-api-audience>
MONOCLOUD_BACKEND_CLIENT_ID=<your-client-id>
MONOCLOUD_BACKEND_CLIENT_SECRET=<your-client-secret>
MONOCLOUD_BACKEND_INTROSPECT_JWT_TOKENS=true

Where to find these values

Environment variableWhere to find the value in MonoCloud
MONOCLOUD_BACKEND_CLIENT_IDClient ID from your API settings
MONOCLOUD_BACKEND_CLIENT_SECRETClient Secret from your API settings

Setting MONOCLOUD_BACKEND_INTROSPECT_JWT_TOKENS to true ensures that JWT access tokens are introspected by the authorization server rather than validated locally.

Protect routes with introspection

protectApi() automatically reads the introspection configuration from environment variables.

src/server.ts
import "dotenv/config";
import Fastify from "fastify";
import {
  protectApi,
  type AuthenticatedFastifyRequest,
} from "@monocloud/backend-node/fastify";

const app = Fastify();

const protect = protectApi();

// All routes require a valid access token (validated through introspection)
app.addHook("onRequest", protect());

app.get("/api/data", async (request) => {
  const { claims } = request as AuthenticatedFastifyRequest;
  return { claims };
});

app.listen({ port: 3000 }, (err) => {
  if (err) throw err;
  console.log("Server running on http://localhost:3000");
});

How it works:

  • The hook sends the access token to the authorization server's introspection endpoint
  • The authorization server validates the token and returns the token's claims
  • If MONOCLOUD_BACKEND_INTROSPECT_JWT_TOKENS is true, JWT tokens are also introspected instead of validated locally
  • Invalid or revoked tokens receive a 401 Unauthorized response
© 2024 MonoCloud. All rights reserved.