---
title: "OAuth"
description: "Make a Nuxt MCP server an OAuth 2.1 resource server, verify JWT or opaque access tokens, serve RFC 9728 discovery metadata, and read verified claims in tools."
canonical_url: "https://mcp-toolkit.nuxt.dev/authentication/oauth"
---
# OAuth

> Make a Nuxt MCP server an OAuth 2.1 resource server, verify JWT or opaque access tokens, serve RFC 9728 discovery metadata, and read verified claims in tools.

With OAuth, your MCP server is a **resource server**: it verifies access tokens and never issues them. Your authorization server (such as Better Auth, Clerk, Okta, or WorkOS) handles sign-in, consent, and token issuance. Configure `oauth` in the server's `index.ts`, and MCP clients discover the authorization server automatically and sign the user in, following the [MCP authorization specification](https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization).

## How a client signs in

1. The client calls `/mcp` without a token and gets `401` with `WWW-Authenticate: Bearer resource_metadata="…", scope="…"`.
2. It fetches the protected-resource metadata ([RFC 9728](https://datatracker.ietf.org/doc/html/rfc9728)), which names your authorization server.
3. It registers, sends the user to sign in and consent, and receives an access token bound to your MCP URL.
4. It calls `/mcp` with `Authorization: Bearer <token>`. The module verifies the token and attaches its claims to `event.context.oauth`.

The following diagram maps those four steps across the MCP client, your Nuxt MCP server, and your authorization server:

<auth-oauth-flow>



</auth-oauth-flow>

The toolkit handles steps 1, 2, and 4. Your authorization server handles step 3.

## Configure it

```ts [server/mcp/index.ts]
import { createMcpOAuth, defineMcpServer } from '@nuxtjs/mcp-toolkit/server'

export default defineMcpServer({
  oauth: createMcpOAuth({
    resource: 'https://example.com/mcp',
    authorizationServers: ['https://auth.example.com'],
    jwt: { jwks: 'https://auth.example.com/.well-known/jwks.json' },
    scopesSupported: ['profile:read', 'projects:write'],
  }),
})
```

- `resource` is the public URL of this endpoint. It must use HTTPS in production (loopback HTTP such as `http://localhost:3000/mcp` is allowed in development), contain no query, fragment, or credentials, and match the server's route path. Trailing slashes are stripped.
- `authorizationServers` lists the issuers that mint tokens for this resource. JWT `iss` must match one of them unless `jwt.issuer` overrides it.
- `scopesSupported` is advertised in the protected-resource metadata and in the `401` challenge so clients request those scopes up front.

The module mounts the metadata route at `/.well-known/oauth-protected-resource/mcp` (with the endpoint path appended), including CORS headers and `OPTIONS` preflight support. A server without OAuth answers `404` there.

Prefer a [provider adapter](https://mcp-toolkit.nuxt.dev/authentication/providers) when you use Better Auth, Clerk, Okta, or WorkOS: each adapter fills these options from the provider's conventions.

## Read the verified identity

```ts [server/mcp/tools/whoami.ts]
import { z } from 'zod'
import { defineMcpTool } from '@nuxtjs/mcp-toolkit/server'

export default defineMcpTool({
  description: 'Read the signed-in user',
  scopes: ['profile:read'],
  outputSchema: z.object({ userId: z.string(), email: z.string().optional() }),
  handler: (event) => {
    const { sub, email } = event.context.oauth!
    return { userId: sub!, email }
  },
})
```

`event.context.oauth` holds the verified token claims: `sub`, `iss`, `aud`, `scope`, `azp`, `email`, and any custom claims the provider includes. The toolkit clears any previous value before verification and only populates it after the token passes.

## Restrict the whole server

`authorize` runs after token verification on every request, receiving the verified identity (with a guaranteed non-empty `sub`) and the request event:

```ts [server/mcp-admin/index.ts]
import { createMcpOAuth, defineMcpServer } from '@nuxtjs/mcp-toolkit/server'
import { isTeamMember } from '../utils/team'

export default defineMcpServer({
  oauth: createMcpOAuth({
    resource: 'https://example.com/mcp/admin',
    authorizationServers: ['https://auth.example.com'],
    jwt: { jwks: 'https://auth.example.com/.well-known/jwks.json' },
  }),
  authorize: async ({ sub }) => isTeamMember(sub),
})
```

Returning `false` answers `403` with no `WWW-Authenticate` challenge, so the client doesn't loop trying to sign in again. Because `authorize` runs on every call, removing someone from the team revokes access immediately even while their access token is still unexpired.

## JWT verification

With `jwt`, each token's signature is verified against the remote JWKS (with a 5-second clock tolerance), along with:

<table>
<thead>
  <tr>
    <th>
      Check
    </th>
    
    <th>
      Default
    </th>
    
    <th>
      Option
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      Issuer
    </td>
    
    <td>
      <code>
        authorizationServers
      </code>
    </td>
    
    <td>
      <code>
        jwt.issuer
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      Audience
    </td>
    
    <td>
      <code>
        resource
      </code>
    </td>
    
    <td>
      <code>
        jwt.audience
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      Expiry
    </td>
    
    <td>
      <code>
        exp
      </code>
      
       is required
    </td>
    
    <td>
      
    </td>
  </tr>
  
  <tr>
    <td>
      Subject
    </td>
    
    <td>
      non-empty <code>
        sub
      </code>
      
       is required
    </td>
    
    <td>
      
    </td>
  </tr>
  
  <tr>
    <td>
      Client
    </td>
    
    <td>
      not checked
    </td>
    
    <td>
      <code>
        jwt.authorizedParties
      </code>
      
       (allowed <code>
        azp
      </code>
      
       values)
    </td>
  </tr>
  
  <tr>
    <td>
      Header type
    </td>
    
    <td>
      not checked
    </td>
    
    <td>
      <code>
        jwt.typ
      </code>
      
      , such as <code>
        'at+jwt'
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      Extra claims
    </td>
    
    <td>
      none (in addition to <code>
        exp
      </code>
      
       and <code>
        sub
      </code>
      
      )
    </td>
    
    <td>
      <code>
        jwt.requiredClaims
      </code>
    </td>
  </tr>
</tbody>
</table>

Setting `jwt.audience: false` turns off the built-in audience check and requires a `verify` callback that validates resource binding itself. `authorizedParties` restricts which client (`azp`) may call the server; it doesn't replace the audience check.

## Opaque tokens and custom verification

For opaque tokens or provider-specific checks, pass `verify(token, event)`:

```ts [server/mcp/index.ts]
import { createMcpOAuth, defineMcpServer } from '@nuxtjs/mcp-toolkit/server'
import { introspect } from '../utils/introspect'

export default defineMcpServer({
  oauth: createMcpOAuth({
    resource: 'https://example.com/mcp',
    authorizationServers: ['https://auth.example.com'],
    verify: async (token, event) => {
      const result = await introspect(token)
      if (!result.active || result.aud !== 'https://example.com/mcp') return false
      event.context.oauth = { sub: result.sub, scope: result.scope }
      return true
    },
  }),
})
```

Your callback must confirm the token is active and bound to this resource, assign the verified claims to `event.context.oauth`, and return `true`. Populate `sub` for `authorize` and `scope` (or `scp`) for scopes. When both `jwt` and `verify` are set, JWT verification runs first. Decoding a JWT without verifying its signature, or reading a session cookie, isn't valid verification.

## Limits

- **Bearer only.** DPoP and other proof-bound tokens are refused: built-in JWT verification rejects any token carrying a `cnf` claim. A custom `verify` callback must do the same.
- **Not an authorization server.** The toolkit mints no tokens and stores no OAuth state.
- **Revocation.** A locally verified JWT remains valid until `exp`. Keep access tokens short-lived (for example 15 minutes) or check revocation inside `authorize`.
- **Bundle size.** When no server or app code uses OAuth, production builds tree-shake `jose` out.

## Static configuration

JWT OAuth can also live in `nuxt.config.ts` under `mcp.oauth` or `mcp.servers.<name>.oauth`, using the same `resource`, `authorizationServers`, `jwt`, and `scopesSupported` fields. Those values are embedded in the build and can't use `verify`, `authorize`, or runtime `serviceTokens`.

When static `oauth` sets `authorizationServer`, the module also proxies that issuer's metadata at the site root (`/.well-known/oauth-authorization-server`) for older MCP clients. Configuring `oauth` in `index.ts` doesn't mount that root route automatically; if older clients need it, add a `server/routes/.well-known/oauth-authorization-server.ts` route yourself. Configure authentication for each server in one place only.

## Test the deployed flow

Verify discovery and challenges against your deployed URL with `curl`:

```bash [Check 401 challenge and metadata]
curl -i -X POST https://example.com/mcp
# HTTP/2 401
# www-authenticate: Bearer realm="mcp", resource_metadata="https://example.com/.well-known/oauth-protected-resource/mcp", scope="profile:read projects:write"

curl https://example.com/.well-known/oauth-protected-resource/mcp
# {"resource":"https://example.com/mcp","authorization_servers":["https://auth.example.com"],"bearer_methods_supported":["header"],"scopes_supported":["profile:read","projects:write"]}
```

Then confirm the remaining cases end to end:

- A valid token succeeds; an expired token or one for another audience or issuer returns `401`.
- `authorize` returning `false` answers `403` with no `WWW-Authenticate` header.
- A missing scope answers `403` with `error="insufficient_scope"` on the modern revision (see [scopes](https://mcp-toolkit.nuxt.dev/authentication/scopes)).
- Two different signed-in users see only their own records.

Finish by completing a real sign-in and token refresh with each MCP client you support. Local JWT unit tests don't prove that your provider's consent screen and refresh flow work.


## Sitemap

See the full [sitemap](https://mcp-toolkit.nuxt.dev/sitemap.md) for all pages.
