pbauth / Docs
Run an OAuth 2.1 and MCP server
github.com/fcakyon/pbauth/oauth adds an OAuth 2.1 authorization server, Protected Resource Metadata, Client ID Metadata Documents (CIMD), Dynamic Client Registration (DCR), optional SEP-990 ID-JAG (EnterpriseAuth), and Model Context Protocol (MCP) middleware inside your PocketBase Go binary.
Set up the Go server
Register the OAuth database migrations alongside pbauth.RegisterMigrations(), configure your resource path and scopes, and mount both the OAuth endpoints and protected MCP handler inside app.OnServe().
app := pocketbase.New()
pbauth.RegisterMigrations()
oauth.RegisterMigrations()
pbCfg := pbauth.Config{
EmailAuth: pbauth.EmailAuthFromEnv(), ExposeMethodsRoute: true,
}
pbauth.Register(app, pbCfg)
oauthSrv := oauth.NewServer(app, oauth.Config{
Auth: pbCfg, PublicURL: "https://api.your_app.example",
ResourcePath: "/mcp", ResourceName: "Acme MCP",
Scopes: []oauth.Scope{
{Name: "notes:read", Title: "Read notes", Default: true},
{Name: "notes:write", Title: "Write notes"},
},
})
app.OnServe().BindFunc(func(se *core.ServeEvent) error {
if err := oauthSrv.Mount(se); err != nil { return err }
oauthSrv.MountProtectedHTTP(se.Router, "/mcp", mcpHandler)
return se.Next()
})For setups without extra OnServe routes, call oauth.Register(app, cfg) or attach oauthSrv.ServeHook(). Mount (invoked by Register and ServeHook) schedules hourly oauthSrv.Cleanup() pruning for expired codes, revoked grants, and redeemed JTIs.
Endpoints and discovery metadata
With default RoutePrefix: "/oauth" and ResourcePath: "/mcp", Mount exposes discovery, authorization, grant, and revocation routes:
| Endpoint | Purpose |
|---|---|
/.well-known/oauth-protected-resource | RFC 9728 metadata for the root resource |
/.well-known/oauth-protected-resource/mcp | RFC 9728 metadata for ResourcePath and each ResourceAliases entry |
/.well-known/oauth-authorization-server | RFC 8414 metadata advertising client_id_metadata_document_supported: true |
/.well-known/openid-configuration | OpenID Discovery alias of the OAuth 2.1 server metadata |
POST /oauth/register | RFC 7591 Dynamic Client Registration (rate-limited when EnableDCR is enabled) |
GET /oauth/request | Pre-validates authorize parameters before login and resolves client metadata |
POST /oauth/consent | Authenticated approval endpoint returning redirect_to, code, state, and iss |
POST /oauth/token | Issues tokens for authorization_code, refresh_token, and jwt-bearer grants |
POST /oauth/revoke | RFC 7009 token revocation (returns HTTP 200) |
GET /oauth/grants | Lists non-revoked grants owned by the authenticated user (expired grants are pruned after 7 days) |
DELETE /oauth/grants/{id} | Revokes one user-owned grant and clears its active tokens |
Client registration and lookup
pbauth resolves client_id values across live CIMD metadata documents, bundled MCP defaults, and DCR registrations in a fixed order:
| Lookup path | When it runs | Security rules |
|---|---|---|
| Live CIMD fetch | HTTPS URL client_id with non-root path | Exact client_id match, 64 KB cap, 5s timeout, zero redirects, SSRF private-IP blocking |
PredefinedClients | Non-URL aliases or offline ErrCIMDUnavailable fallback | Defaults to oauth.DefaultMCPClients() (Claude, Claude Code, ChatGPT) |
| Dynamic Client Registration | Clients created via POST /oauth/register | HTTPS or loopback redirects capped by MaxDCRRedirectURIs (default 5) |
Loopback redirects for localhost, 127.0.0.1, and ::1 follow RFC 8252 Section 7.3 and permit ephemeral ports even when a fixed port was registered. To test CIMD against a local test fixture, set AllowLoopbackCIMDHTTP: true.
Tokens, scopes, and consent security
Every authorization, rotation, and consent response enforces strict cryptographic and origin controls:
- Mandatory PKCE:
code_challenge(S256) is verified on every authorization code flow withredirect_uribound on the code - Default scope fallback: Generic scopes (
openid,profile,email,offline_access) are ignored unless declared inConfig.Scopes, falling back to configured default scopes - Hashed storage: Access tokens (
your_token_prefix+at_…), codes (ac_…), and refresh tokens (rt_…) are stored hashed in collections withnilAPI rules ("pbo_"prefix by default) - Replay-safe rotation: Refresh token exchanges rotate both tokens with a
60sretry grace window (RefreshReplayGrace) and a 32-entry history ring that revokes the grant on replay - Bound consent checks:
POST /oauth/consentchecksexpected_user_idagainst the session and returnsiss(RFC 9207) - Frame protection: Attach
oauth.ConsentPageHeaders()on your consent route to setX-Frame-Options: DENY,frame-ancestors 'none',Cache-Control: no-store, andX-Robots-Tag: noindex, nofollow
Publish a SEP-2127 server card
Set Config.ServerCard to serve pre-connection MCP metadata at your_resource_path/server-card and /.well-known/ai-catalog.json:
ServerCard: &oauth.ServerCard{
Name: "com.example/notes-mcp",
Title: "Acme Notes",
Description: "Read and manage Acme Notes from any MCP client.",
Version: "0.3.0",
WebsiteURL: "https://your_app.example",
Remotes: []oauth.ServerCardRemote{
{Type: "streamable-http", URL: "https://api.your_app.example/mcp"},
},
}Accept Enterprise ID-JAG assertions
Configure Config.EnterpriseAuth to exchange external identity provider oauth-id-jag+jwt assertions for scoped access tokens:
EnterpriseAuth: &oauth.EnterpriseConfig{
TrustedIssuerResolver: oauth.SingleTenantIssuer(
"https://idp.your_app.example", "notes:read",
),
ResolveSubject: func(
ctx context.Context, tx core.App, c oauth.SubjectClaims,
) (*core.Record, error) {
return tx.FindAuthRecordByEmail("users", c.Email)
},
}Token exchange enforces these checks before issuing an access token:
- JWT claims and signature: Verifies
typ == "oauth-id-jag+jwt", trustediss, matchingaudandresource, RSA (>= 2048) or EC P-256 keys from SSRF-safe JWKS discovery,300slifetime, and30sclock skew - Atomic replay defense: Stores
(iss, jti)inside the token transaction so assertions execute once - Active local account: Verifies
IsAuthorizedUserand looks up existing records without auto-provisioning
Protect MCP and HTTP handlers
Wrap PocketBase routes with MountProtectedHTTP (or standard handlers with ProtectedMiddleware) to validate scopes, origins, and rate limits:
oauthSrv.MountProtectedHTTP(se.Router, "/mcp", mcpHandler,
oauth.WithRequiredScopes("notes:read"),
oauth.WithRateLimit(600),
)Read token metadata inside handlers via oauth.TokenInfoFromContext(r.Context()), enforce per-tool scopes with oauth.RequireScopes(ctx, "notes:write"), and accept existing JWTs alongside OAuth tokens via Config.ExtraTokenVerifier:
| Middleware layer | Behavior |
|---|---|
| Origin and Host validation | Enforces exact Origin allowlists (default Issuer()) and loopback host matching |
| Accept header normalization | Clones POST requests to include application/json and text/event-stream |
| Bearer auth and scopes | Validates tokens before HTTP method checks and sets WWW-Authenticate Bearer resource_metadata=… on 401/403 |
| Per-grant rate limiter | Caps requests per grant and returns 429 with Retry-After: 60 |
Override collection names
Pass oauth.CollectionNames to both RegisterMigrations and oauth.Config when your database already has conflicting collection names:
names := oauth.CollectionNames{
Clients: "mcp_oauth_clients", Codes: "mcp_oauth_codes",
Tokens: "mcp_oauth_tokens", JTIs: "mcp_oauth_jtis",
Users: "users",
}
oauth.RegisterMigrations(names)
oauth.Register(app, oauth.Config{Collections: names})React components
Import pocketbase-auth/oauth and pbauth.css to render authorization consent, grant management, and MCP onboarding UIs without bundling them into login-only pages.
Consent screen (OAuthConsentCard) | Connected apps (ConnectedApps) | MCP client onboarding (MCPSetupCard) |
|---|---|---|
![]() | ![]() | ![]() |
Use the three exported components to cover your authorize and integration settings routes:
import PocketBase from "pocketbase";
import "pocketbase-auth/pbauth.css";
import { ConnectedApps, MCPSetupCard } from "pocketbase-auth/oauth";
import { OAuthConsentCard, createPBOAuthClient } from "pocketbase-auth/oauth";
const pb = new PocketBase(window.location.origin);
const oauth = createPBOAuthClient(pb);
const mcpUrl = "https://api.your_app.example/mcp";
export const AuthorizePage = () => <OAuthConsentCard client={oauth} />;
export const IntegrationsPage = () => (
<>
<MCPSetupCard mcpUrl={mcpUrl} serverName="Acme" />
<ConnectedApps client={oauth} hideWhenEmpty />
</>
);Each component pairs with AuthCard and supports shared localization and RTL props:
| Component | Key capabilities | Notable props |
|---|---|---|
<OAuthConsentCard /> | Pre-validates /oauth/request, renders inline AuthCard when signed out, assigns verified client logos only from verified hosts or predefined connector IDs, switches accounts, checks expected_user_id | appName, appIcon, clientIcon, brand, showScopeCodes, scopeLabels, renderSignIn, authCardProps, onRedirect |
<ConnectedApps /> | Loads GET /oauth/grants, shows client logos and verified hosts, displays scope tags and last-used dates, and revokes tokens via DELETE /oauth/grants/{id} (404 idempotent) | scopeLabels, hideWhenEmpty, onGrantsLoaded, onRevoke |
<MCPSetupCard /> | Copyable MCP URL, deep links for Claude and ChatGPT, and setup snippets for Claude Code, Codex CLI, VS Code, Cursor, Gemini CLI, and T3 Code | mcpUrl, serverName, defaultClient, onCopy, docsHref, docsLabel |


