Token inspector
A decoded token with its claims explained: audience, scopes, the actor chain and the key that it is bound to.
A teaching tool. It decodes a token in the browser and says, in one line each, what the claims that matter mean. The applications in this catalog use it in their "How this works" panel.
Installation
- CLI
- Manual
The command adds the file to your project, with the shadcn/ui components that it uses. Your project needs shadcn/ui.
- pnpm
- npm
- yarn
- bun
pnpm dlx shadcn@latest add https://examples.lumoauth.dev/r/token-inspector.json
npx shadcn@latest add https://examples.lumoauth.dev/r/token-inspector.json
yarn dlx shadcn@latest add https://examples.lumoauth.dev/r/token-inspector.json
bunx --bun shadcn@latest add https://examples.lumoauth.dev/r/token-inspector.json
Add the shadcn/ui components that the pattern uses.
npx shadcn@latest add badge collapsibleInstall the packages.
npm install lucide-reactCopy the code into your project.
components/token-inspector.tsx'use client';import * as React from 'react';import { ChevronRight, CircleAlert, Clock, ShieldCheck, ShieldQuestion } from 'lucide-react';import { Badge } from '@/components/ui/badge';import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';import { cn } from '@/lib/utils';type Json = Record<string, any>;function decodePart(part: string): Json | null {try {const json = atob(part.replace(/-/g, '+').replace(/_/g, '/'));return JSON.parse(decodeURIComponent(escape(json)));} catch {return null;}}/** Splits a JWT. It does NOT check the signature: do that on your server. */export function decodeToken(token: string): { header: Json; payload: Json } | null {const parts = token.trim().split('.');if (parts.length !== 3) return null;const header = decodePart(parts[0]);const payload = decodePart(parts[1]);return header && payload ? { header, payload } : null;}const time = (seconds: number) => new Date(seconds * 1000).toLocaleString([], { dateStyle: 'medium', timeStyle: 'medium' });const list = (value: unknown) => (Array.isArray(value) ? value.join(', ') : String(value));/** The claims that matter, in reading order, each with one line of plain words. */const CLAIMS: Array<{ key: string; label: string; text: (v: any, p: Json) => string; value?: (v: any) => React.ReactNode }> = [{ key: 'iss', label: 'Issuer', text: () => 'The organization that issued the token.' },{ key: 'sub', label: 'Subject', text: (_, p) => (p.act ? 'The person or service on whose behalf the caller acts.' : 'Who the token is about.') },{key: 'act', label: 'Actor', text: () => 'The caller acts for the subject. A nested actor handed the work on.',value: (v) => {const chain: string[] = [];for (let act = v; act && typeof act === 'object'; act = act.act) if (act.sub) chain.push(String(act.sub));return chain.join(' ← ');},},{ key: 'aud', label: 'Audience', text: () => 'The API that may accept this token. Every other API must refuse it.', value: list },{ key: 'scope', label: 'Scopes', text: () => 'What the token allows.', value: (v) => String(v).split(' ').join(', ') },{key: 'authorization_details', label: 'Approved detail', text: () => 'The exact action that a person approved. The API must compare it with the request.',value: (v) => JSON.stringify(v),},{ key: 'cnf', label: 'Bound to a key', text: () => 'The caller must prove, with each request, that it holds this key (DPoP).', value: (v) => v?.jkt ?? JSON.stringify(v) },{ key: 'client_id', label: 'Client', text: () => 'The application or the agent that asked for the token.' },{ key: 'exp', label: 'Expires', text: () => 'The token is refused after this time.', value: time },{ key: 'iat', label: 'Issued', text: () => 'When the token was issued.', value: time },];export interface TokenInspectorProps {/** A JWT: an access token or an ID token. */token: string;/*** The result of the signature check that your server made.* Leave it out when the token was not verified: the panel then says so.*/verified?: boolean;/** A name for the token, for example "Token for the invoices API". */title?: string;className?: string;}export function TokenInspector({ token, verified, title = 'Token', className }: TokenInspectorProps) {const decoded = React.useMemo(() => decodeToken(token), [token]);const [open, setOpen] = React.useState(false);// The clock is read after the first render, so that a server can render the panel.const [now, setNow] = React.useState<number | null>(null);React.useEffect(() => {setNow(Math.floor(Date.now() / 1000));const timer = setInterval(() => setNow(Math.floor(Date.now() / 1000)), 1000);return () => clearInterval(timer);}, []);if (!decoded) {return (<div className={cn('flex w-full max-w-lg items-center gap-2 rounded-lg border p-3 text-sm text-muted-foreground', className)}><CircleAlert className="size-4" aria-hidden="true" />This is not a JWT. An opaque token has no claims to read: ask LumoAuth about it with token introspection.</div>);}const { header, payload } = decoded;const hasExpiry = typeof payload.exp === 'number';const left = hasExpiry && now !== null ? payload.exp - now : null;const expired = left !== null && left <= 0;const VerifiedIcon = verified ? ShieldCheck : ShieldQuestion;return (<section className={cn('w-full max-w-lg rounded-lg border bg-card text-sm text-card-foreground', className)} aria-label={title}><header className="flex flex-wrap items-center gap-2 border-b px-3 py-2"><h3 className="mr-auto font-medium">{title}</h3>{header.typ && <Badge variant="outline" className="font-mono font-normal">{String(header.typ)}</Badge>}{payload.act && <Badge variant="secondary">Delegated</Badge>}{payload.cnf && <Badge variant="secondary">DPoP-bound</Badge>}<BadgeclassName={cn('border-transparent',verified === true && 'bg-emerald-500/15 text-emerald-700 dark:text-emerald-400',verified === false && 'bg-red-500/15 text-red-700 dark:text-red-400',verified === undefined && 'bg-muted text-muted-foreground',)}><VerifiedIcon aria-hidden="true" />{verified === true ? 'Signature verified' : verified === false ? 'Signature not valid' : 'Signature not checked'}</Badge></header><dl>{CLAIMS.filter((claim) => payload[claim.key] !== undefined).map((claim) => (<div key={claim.key} className="grid gap-x-3 gap-y-0.5 border-b px-3 py-2 sm:grid-cols-[8.5rem_1fr]"><dt className="font-medium">{claim.label}<span className="ml-1.5 font-mono text-xs font-normal text-muted-foreground">{claim.key}</span></dt><dd className="min-w-0"><pclassName={cn('font-mono text-xs leading-5 break-words', claim.key === 'exp' && expired && 'text-red-700 dark:text-red-400')}// Times are formatted for the reader, which a server cannot know.suppressHydrationWarning>{claim.value ? claim.value(payload[claim.key]) : String(payload[claim.key])}</p><p className="text-xs text-muted-foreground">{claim.text(payload[claim.key], payload)}</p></dd></div>))}</dl><div className="flex items-center gap-2 border-b px-3 py-2 text-xs"><Clock className="size-3.5 text-muted-foreground" aria-hidden="true" />{!hasExpiry ? (<span className="text-muted-foreground">The token has no expiry time.</span>) : left === null ? (<span className="text-muted-foreground">Checking the expiry time…</span>) : expired ? (<span className="font-medium text-red-700 dark:text-red-400">Expired</span>) : (<span className="text-muted-foreground tabular-nums">Valid for {left >= 3600 ? `${Math.floor(left / 3600)} h ` : ''}{Math.floor((left % 3600) / 60)} min {left % 60} s</span>)}</div><Collapsible open={open} onOpenChange={setOpen}><CollapsibleTrigger className="flex w-full items-center gap-1.5 px-3 py-2 text-xs text-muted-foreground outline-none hover:text-foreground focus-visible:text-foreground"><ChevronRight className={cn('size-3.5 transition-transform', open && 'rotate-90')} aria-hidden="true" />Header and every claim</CollapsibleTrigger><CollapsibleContent><pre className="overflow-x-auto border-t bg-muted/40 px-3 py-2 font-mono text-xs leading-5">{JSON.stringify({ header, payload }, null, 2)}</pre></CollapsibleContent></Collapsible></section>);}Change the import paths if your project keeps its components in another place.
Usage
Pass a token. Pass verified only when your server checked the signature.
import { TokenInspector } from '@/components/token-inspector';
export function DebugToken({ token, verified }: { token: string; verified?: boolean }) {
return <TokenInspector token={token} verified={verified} title="Token for the invoices API" />;
}
The inspector decodes. It does not verify. A browser cannot be trusted with that check, so do it on your server:
import { AccessTokenError, createAccessTokenVerifier } from '@lumoauth/agent';
const verifier = createAccessTokenVerifier({
issuer: 'https://app.lumoauth.dev/orgs/acme-corp/api/v1',
resource: 'https://api.acme.example/invoices',
});
export async function isVerified(token: string) {
try {
await verifier.verify(token);
return true;
} catch (error) {
if (error instanceof AccessTokenError) return false;
throw error;
}
}
Show a token only to the person or the agent that it belongs to, and only in a tool for developers. An access token is a credential.
Where the data comes from
| What the pattern shows | Call |
|---|---|
| The claims | The token itself. Nothing is sent anywhere. |
| The signature check | verifyAccessToken() or createAccessTokenVerifier() of @lumoauth/agent, on your server |
| An opaque token | Token introspection, POST /oauth/introspect |
States
- Not checked. Without
verified, the badge says that nobody checked the signature. - Expired, with a signature that is not valid.
- Not a JWT. An opaque token has no claims to read.
Props
| Prop | Type | Default | Description |
|---|---|---|---|
tokenrequired | string | A JWT: an access token or an ID token. | |
verified | boolean | The result of the signature check that your server made. Leave it out when the token was not verified. | |
title | string | 'Token' | A name for the token. |
className | string | Class name for the panel. |