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 exampleDirect link to Usage example
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:
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 IDDirect 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 parametersDirect link to Constructor parameters
secret?:
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?:
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?:
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?:
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.