Skip to content

auth-agent: lightweight JWT authentication example#948

Merged
threepointone merged 14 commits into
mainfrom
example/auth-agent
Mar 2, 2026
Merged

auth-agent: lightweight JWT authentication example#948
threepointone merged 14 commits into
mainfrom
example/auth-agent

Conversation

@Muhammad-Bin-Ali
Copy link
Copy Markdown
Contributor

@Muhammad-Bin-Ali Muhammad-Bin-Ali commented Feb 19, 2026

examples/auth-agent — protect agent connections with JWTs

Example showing how to authenticate WebSocket and HTTP connections to a Cloudflare Agent using JWTs.

What it demonstrates

  • onBeforeConnect — verify a JWT query param before upgrading to WebSocket
  • onBeforeRequest — verify a JWT (Bearer header or query param) before handling HTTP requests
  • A demo /api/token endpoint that issues JWTs with jose (HMAC-SHA256, iss/aud claims)
  • Passing user identity from JWT claims into the AI chat system prompt

Key patterns

routeAgentRequest(request, env, {
  onBeforeConnect: async (req) => {
    const token = new URL(req.url).searchParams.get("token");
    const payload = await verifyToken(env, token);
    if (!payload) return Response.json({ error: "Unauthorized" }, { status: 401 });
    return req;
  },
  onBeforeRequest: async (req) => {
    const authHeader = req.headers.get("Authorization");
    const token = authHeader?.startsWith("Bearer ") ? authHeader.slice(7)
      : new URL(req.url).searchParams.get("token");
    const payload = await verifyToken(env, token);
    if (!payload) return Response.json({ error: "Unauthorized" }, { status: 401 });
    return req;
  }
});

The token endpoint is demo scaffolding — in production, replace it with your own auth service. The onBeforeConnect / onBeforeRequest middleware stays the same.

Files

File Purpose
src/server.ts Worker entry — token endpoint, JWT verify, chat agent
src/auth-client.ts Client-side token fetch and storage
src/client.tsx React UI — name form + chat
README.md Docs with copy-paste patterns

@Muhammad-Bin-Ali Muhammad-Bin-Ali self-assigned this Feb 19, 2026
@changeset-bot
Copy link
Copy Markdown

changeset-bot Bot commented Feb 19, 2026

⚠️ No Changeset found

Latest commit: 6900f49

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@pkg-pr-new
Copy link
Copy Markdown

pkg-pr-new Bot commented Feb 19, 2026

Open in StackBlitz

npm i https://pkg.pr.new/agents@948
npm i https://pkg.pr.new/@cloudflare/ai-chat@948
npm i https://pkg.pr.new/@cloudflare/codemode@948
npm i https://pkg.pr.new/hono-agents@948

commit: 93723d5

@Muhammad-Bin-Ali Muhammad-Bin-Ali requested a review from a team February 20, 2026 20:08
Comment thread examples/auth-agent/src/auth.ts Outdated
Comment thread examples/auth-agent/src/index.tsx Outdated
Comment thread examples/auth-agent/src/client.tsx Outdated
Comment thread examples/auth-agent/src/client.tsx Outdated
Comment thread examples/auth-agent/src/client.tsx Outdated
Comment thread examples/auth-agent/README.md Outdated
Comment thread examples/auth-agent/tsconfig.json Outdated
Comment thread examples/auth-agent/src/client.tsx Outdated
@Muhammad-Bin-Ali Muhammad-Bin-Ali force-pushed the example/auth-agent branch 2 times, most recently from 4be1e5b to dc9304d Compare February 25, 2026 18:19
Comment thread examples/auth-agent/README.md Outdated
Muhammad Ali and others added 14 commits March 2, 2026 09:03
Co-authored-by: deathbyknowledge <sjames@cloudflare.com>
Replace the previous better-auth + D1 example with a minimal JWT demo. Server now exposes a demo /api/token (HMAC HS256 via AUTH_SECRET) and verifies tokens in onBeforeConnect/onBeforeRequest; Durable Object renamed to ChatAgent and uses the token sub claim as the DO name. Client-side auth simplified to name-based token issuance/storage and UI adjusted accordingly. Removed D1 schema/sql and better-auth integration, updated env types, wrangler config (AI binding), package metadata, added favicon, and bumped some deps and UI styles. This refactors the example to be a smaller, copyable pattern for protecting WebSocket/HTTP agent routes while keeping the token issuance endpoint as demo scaffolding to be replaced in production.
@threepointone threepointone changed the title Add an example to showcase how to setup authentication with better-auth. Rewrite auth-agent example: JWT-only auth, remove D1 and better-auth Mar 2, 2026
@threepointone threepointone changed the title Rewrite auth-agent example: JWT-only auth, remove D1 and better-auth auth-agent: lightweight JWT authentication example Mar 2, 2026
@threepointone
Copy link
Copy Markdown
Contributor

this felt too heavy for an example, so I rewrote it to be jwt only and more as a guide. thanks for the pr!

@threepointone threepointone merged commit 28b2dbb into main Mar 2, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants