Skip to content
LogoLogo

Authenticate requests

An app sends the access token of a session to an API, and the API verifies the token.

Overview

An app sends the session's access token, a JWT that names the user and the app. The API verifies it with the tokens plugin, against Tempo ID's key set, with no call to Tempo ID for each request.

The demo calls a route of the site with the session's access token, and the route returns the token's user ID. A call without the access token receives 401.

Authenticate a requestDemo

Walkthrough

The steps build a React app and the API that it calls.

Install the packages

Install accounts with Viem, in the app and in the API.

Send the access tokenClient

session.fetch sends the access token as a Bearer token, and refreshes it first if it expires soon. The react plugin adds useSession.

import { useState } from 'react'
import { accounts } from './tempo.config.js'
 
export function App() {
  const { isPending, session } = accounts.useSession()
  const [userId, setUserId] = useState<string>()
 
  async function call() {
    const response = await accounts.session.fetch({
      url: 'https://api.example/me',
    })
    const body = (await response.json()) as { userId: string }
    setUserId(body.userId)
  }
 
  if (isPending) return <p>Checking your session…</p>
  if (!session)
    return (
      <button onClick={() => accounts.dialog.signIn()} type="button">
        Sign in
      </button>
    )
  return (
    <>
      <button onClick={call} type="button">
        Call the API
      </button>
      {userId && <p>The API read the user {userId}.</p>}
    </>
  )
}

Create the instanceServer

In the API, the tokens plugin adds tokens.verifyAccessToken. It accepts only the access tokens of the app's clientId, such as the page's origin. Create the instance once, since it keeps Tempo ID's key set for 10 minutes.

server.ts
import { Accounts } from 'accounts'
import { tokens } from 'accounts/plugins'
 
const accounts = Accounts.create({
  clientId: 'https://app.example',
  plugins: [tokens()],
})

Read the userServer

tokens.verifyAccessToken reads the token of the authorization header, and checks its signature, type, issuer, audience, expiry, and app. It returns the verified token, or undefined if the request holds no token that verifies.

Without a verified token, the API answers 401. The API also refuses a DPoP token, which names a boundTo, until it refuses a repeated proof, as Bind DPoP keys shows.

server.ts
import { Accounts } from 'accounts'
import { tokens } from 'accounts/plugins'
 
const accounts = Accounts.create({
  clientId: 'https://app.example',
  plugins: [tokens()],
})
 
export default {
  async fetch(request: Request) {
    const token = await accounts.tokens.verifyAccessToken(request) 
    if (!token || token.boundTo)
      return Response.json({ error: 'invalid_token' }, { status: 401 })
 
    return Response.json({ userId: token.userId })
  },
}

If the key set cannot be fetched, the call throws Accounts.RequestError with status 0. The token can still be valid, so the API answers 503, and the app keeps its session, as Limit the fetch of the key set shows.

The token, never a request field, names whose data the API reads or changes:

PropertyNames
accessKeysThe user's live access keys for the app, from the access_keys claim
accountsThe user's Tempo Account addresses, from tempo_accounts. Empty for a third-party app
clientIdThe app that received the token
complianceThe screening state of each address
scopeThe scopes that the app received
userIdThe user, from sub

Use cases

Each use case sets one option of the tokens plugin, which tokens.verifyAccessToken uses, or calls another member of the plugin.

Accept the tokens of several apps

clientIds names each app whose tokens the API accepts. The token's clientId names the app of each request.

server.ts
import { Accounts } from 'accounts'
import { tokens } from 'accounts/plugins'
 
const accounts = Accounts.create({
  clientId: 'https://app.example',
  plugins: [
    tokens({
      clientIds: ['https://app.example', 'https://admin.app.example'], 
    }),
  ],
})

Accept the tokens of every app

A registered resource that any app may call, such as an MCP server, sets clientIds to 'any'. It then names itself in audience, so it accepts only the tokens issued for it. Charge tool calls shows such a server.

server.ts
import { Accounts } from 'accounts'
import { tokens } from 'accounts/plugins'
 
const accounts = Accounts.create({
  clientId: 'https://mcp.example.com',
  plugins: [
    tokens({ audience: 'https://mcp.example.com/mcp', clientIds: 'any' }),
  ],
})

Refuse a removed signing key sooner

maxAge sets how long the key set verifies, in milliseconds. A shorter time refuses the tokens of a removed signing key sooner. Defaults to 10 minutes. Few verifications wait for a fetch of the set:

Age of the key setVerification
Before half of maxAgeVerifies with the set
From half of maxAgeVerifies with the set, and fetches a new set in the background
From maxAge, or no setWaits for a fetch
A token names an unknown kidWaits for a fetch, at most once each 30 seconds
server.ts
import { Accounts } from 'accounts'
import { tokens } from 'accounts/plugins'
 
const accounts = Accounts.create({
  clientId: 'https://app.example',
  plugins: [tokens({ maxAge: 60_000 })], 
})

Keep the key set across instances

Each new process starts without Tempo ID's key set. keySet.cache takes a Store that the instances share, so a new instance verifies with its copy, without a fetch. keySet.defer keeps the background fetches and writes running after the response.

tempo.config.ts
import { Accounts, Store } from 'accounts'
import { createClient } from 'redis'
 
const redis = await createClient({ url: process.env.REDIS_URL }).connect()
 
export const accounts = Accounts.create({
  clientId: 'https://app.example',
  keySet: { cache: Store.redis(redis) }, 
})

Reach Tempo ID at an internal address

If the instance's url reaches Tempo ID at another address, such as an internal host, issuer names Tempo ID's public origin. Each token names that origin as its issuer.

server.ts
import { Accounts } from 'accounts'
import { tokens } from 'accounts/plugins'
 
const accounts = Accounts.create({
  clientId: 'https://app.example',
  plugins: [tokens({ issuer: 'https://id.tempo.xyz' })], 
  url: 'http://tempo-id.internal',
})

Limit the fetch of the key set

timeout sets how long a fetch of the key set may take, in milliseconds. Defaults to 5 seconds. A slower or failed fetch throws Accounts.RequestError with status 0, which the API answers with 503.

server.ts
import { Accounts } from 'accounts'
import { tokens } from 'accounts/plugins'
 
const accounts = Accounts.create({
  clientId: 'https://app.example',
  plugins: [tokens({ timeout: 2_000 })], 
})
 
export default {
  async fetch(request: Request) {
    const token = await accounts.tokens
      .verifyAccessToken(request)
      .catch((error: unknown) => {
        if (error instanceof Accounts.RequestError && error.status === 0)
          return error
        throw error
      })
    if (token instanceof Accounts.RequestError)
      return Response.json(
        { error: 'temporarily_unavailable' },
        { status: 503 },
      )
    if (!token || token.boundTo)
      return Response.json({ error: 'invalid_token' }, { status: 401 })
 
    return Response.json({ userId: token.userId })
  },
}

Read the email address

An access token holds no email address. tokens.userInfo reads the user of a verified token from Tempo ID, as Read users shows.

server.ts
import { Accounts } from 'accounts'
import { tokens } from 'accounts/plugins'
 
const accounts = Accounts.create({
  clientId: 'https://app.example',
  plugins: [tokens()],
})
 
export default {
  async fetch(request: Request) {
    const token = await accounts.tokens.verifyAccessToken(request)
    if (!token || token.boundTo)
      return Response.json({ error: 'invalid_token' }, { status: 401 })
 
    const user = await accounts.tokens.userInfo({ accessToken: token }) 
    return Response.json({ email: user.email })
  },
}

Next steps