Skip to main content

MastraJwtAuth class

The MastraJwtAuth class provides a lightweight authentication mechanism for Mastra using JSON Web Tokens (JWTs). It verifies incoming requests with a shared secret or with the public keys from a JSON Web Key Set (JWKS) endpoint, and integrates with the Mastra server using the auth option.

Usage example
Direct link to Usage example

src/mastra/index.ts
import { Mastra } from '@mastra/core'
import { MastraJwtAuth } from '@mastra/auth'

export const mastra = new Mastra({
server: {
auth: new MastraJwtAuth({
secret: '<your-secret>',
}),
},
})

To verify tokens signed by an identity provider, pass its JWKS URL and issuer instead of a secret:

src/mastra/index.ts
import { Mastra } from '@mastra/core'
import { MastraJwtAuth } from '@mastra/auth'

export const mastra = new Mastra({
server: {
auth: new MastraJwtAuth({
jwksUri: 'https://auth.example.com/.well-known/jwks.json',
issuer: 'https://auth.example.com/',
}),
},
})

User ID
Direct link to User ID

The authenticated user's id is the token's id claim, or its sub claim when the token has no id. RBAC looks up roles by this id, and it owns the records the user creates unless mapUserToResourceId is set. See user IDs from JWT providers.

Constructor parameters
Direct link to Constructor parameters

secret?:

string
= process.env.JWT_AUTH_SECRET
A unique string used to sign and verify JSON Web Tokens (JWTs) for authenticating incoming requests. Falls back to JWT_AUTH_SECRET when omitted. Either a secret or jwksUri is required: the constructor throws an error if neither is set, or if this option is an empty string (an empty string does not fall back to JWT_AUTH_SECRET).

jwksUri?:

string
= process.env.JWT_AUTH_JWKS_URI
URL of a JWKS endpoint. Tokens are verified with the public key matching their kid header, using the algorithm of that key. Keys are cached, and fetches for unknown key IDs are limited to 10 per minute. Falls back to JWT_AUTH_JWKS_URI. Not combinable with secret: the constructor throws if both options are set, or if both JWT_AUTH_SECRET and JWT_AUTH_JWKS_URI are set. An explicit option wins over the environment variable for the other option, so jwksUri ignores JWT_AUTH_SECRET and secret ignores JWT_AUTH_JWKS_URI.

issuer?:

string
= process.env.JWT_AUTH_ISSUER
Expected iss claim. Tokens from another issuer are rejected. The built-in MCP server also advertises it as the authorization server in its OAuth metadata. Falls back to JWT_AUTH_ISSUER.

mapUser?:

(payload: JwtPayload) => User | null
Maps the verified token payload to the user returned by getCurrentUser(). Defaults to reading sub or id, email, name, and avatarUrl, avatar_url, or picture.

When the built-in MCP server's server.mcp.oauth.resource is set, MastraJwtAuth also requires the token's aud claim to include that URL on /api/mcp.

On this page