Skip to content
LogoLogo

Verify ID tokens

A server verifies the ID token of a sign-in before it reads the user from it.

Overview

The ID token is a JWT that names the user to the app. A server that receives one checks its signature, issuer, audience, and expiry, and only then reads its claims. The tokens plugin runs these checks against Tempo ID's key set.

The demo sends the session's ID token to the site's server, which returns its claims, then sends a copy with another email address, which the server refuses.

Verify an ID tokenDemo

Walkthrough

Install the packages

Install accounts with Viem, in the app and on the server.

Create the instanceClient

The page's origin is its client ID, the ID token's aud.

tempo.config.ts
import { Accounts } from 'accounts'
 
export const accounts = Accounts.create({ chain: 'testnet' })

Send the ID tokenClient

The session holds the ID token as idToken, which is optional, since a refresh can return none.

import { accounts } from './tempo.config.js'
 
export function Verify() {
  async function verify() {
    const session = await accounts.dialog.signIn()
 
    const response = await fetch('/api/verify', {
      body: JSON.stringify({ idToken: session.idToken }), 
      headers: { 'content-type': 'application/json' },
      method: 'POST',
    })
    console.log(await response.json())
  }
 
  return (
    <button onClick={() => void verify()} type="button">
      Sign in with Tempo
    </button>
  )
}

Create the server instanceServer

On the server, create an instance with the tokens plugin. Its clientId is the client ID of the app, the origin of the page. The instance keeps Tempo ID's key set for 10 minutes, so create it once.

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

Verify the ID tokenServer

tokens.verifyIdToken returns the claims of the ID token, or undefined if a check fails.

server.ts
import { Accounts } from 'accounts'
import { tokens } from 'accounts/plugins'
 
const accounts = Accounts.create({
  clientId: 'https://app.example',
  plugins: [tokens()],
})
 
export async function handle(request: Request) {
  const { idToken } = (await request.json()) as { idToken: string }
 
  const token = await accounts.tokens.verifyIdToken({ idToken }) 
  if (!token)
    return Response.json({ error: 'invalid_token' }, { status: 401 })
  return Response.json({ email: token.email, id: token.userId })
}
CheckRefuses
SignatureA token that Tempo ID's key set did not sign with RS256
TypeA header typ other than JWT, such as a logout token or access token
IssuerA token of another issuer than Tempo ID
AudienceA token of another app, also one that names the app beside another app
ExpiryA token past its exp
ClaimsA token without email, email_verified, exp, iat, iss, or sub

The audience comes from the instance's clientId, never from a value of the request.

Read the claimsServer

The verified token names the user. Its userId is the id of session.user.

PropertyClaimValue
authTimeauth_timeWhen the user signed in to Tempo ID, in milliseconds
clientIdaudThe client ID of the app
emailemailThe email address of the user
emailVerifiedemail_verifiedtrue
expiresAtexpWhen the ID token expires, in milliseconds: 10 hours after issue
issuedAtiatWhen Tempo ID issued the ID token, in milliseconds
sessionIdsidThe Tempo ID session of the sign-in. Absent without a logout of the app
userIdsubThe ID of the user

Answer the requestServer

Respond with 401 if tokens.verifyIdToken returns undefined. If the server cannot fetch Tempo ID's key set, it throws Accounts.RequestError with status 0. The ID token can still be valid, so respond with 503.

server.ts
import { Accounts } from 'accounts'
import { tokens } from 'accounts/plugins'
 
const accounts = Accounts.create({
  clientId: 'https://app.example',
  plugins: [tokens()],
})
 
export async function handle(request: Request) {
  const { idToken } = (await request.json()) as { idToken: string }
 
  try {
    const token = await accounts.tokens.verifyIdToken({ idToken })
    if (!token)
      return Response.json({ error: 'invalid_token' }, { status: 401 })
    return Response.json({ email: token.email, id: token.userId })
  } catch (error) {
    if (error instanceof Accounts.RequestError && error.status === 0)
      return Response.json(
        { error: 'temporarily_unavailable' },
        { status: 503 },
      )
    throw error
  }
}

Use cases

Each use case sets one option of the tokens plugin, which tokens.verifyIdToken uses.

Accept several apps

A server that receives the ID tokens of several apps names their client IDs in clientIds. The clientId of the verified token names the app of each token.

An ID token names the app itself, so clientIds set to 'any' verifies only the ID tokens of the instance's own clientId.

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.example'] }), 
  ],
})

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',
})

Refresh the key set sooner

maxAge sets how long Tempo ID's 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({
  chain: 'testnet',
  keySet: { cache: Store.redis(redis) }, 
})

Limit the fetch of the key set

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

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

Next steps