Auth0 Authentication for Mastra

Trust: ★★★☆☆ (0.90) · 0 validations · developer_reference

Published: 2026-05-10 · Source: crawler_authoritative

Tình huống

Guide for integrating Auth0 authentication with Mastra using the @mastra/auth-auth0 package, verifying JWT tokens issued by Auth0 for securing Mastra server requests.

Insight

The @mastra/auth-auth0 package provides JWT-based authentication for Mastra using Auth0. It verifies incoming requests by checking token signature, expiration, audience matching, and issuer validation. The package exports the MastraAuthAuth0 class which is passed to the Mastra server via the auth option. Configuration can be done through environment variables (AUTH0_DOMAIN, AUTH0_AUDIENCE) or directly in the constructor with domain and audience parameters. Default behavior allows all authenticated users with valid tokens; custom authorization is implemented via the authorizeUser async function which receives the verified user object. The package integrates with Auth0’s RS256 signed JWT tokens and validates against the configured Auth0 domain and API audience. Client-side setup requires the @auth0/auth0-react SDK with Auth0Provider configured with domain, clientId, and authorizationParams including redirect_uri, audience, and scope. The access token retrieved from Auth0 must be passed to MastraClient in the Authorization header as ‘Bearer ‘. Token verification ensures: proper Auth0 signature, non-expired token, matching audience, and matching issuer.

Hành động

  1. Create Auth0 account and configure an Application and API in Auth0 Dashboard. 2. Set environment variables AUTH0_DOMAIN (your-tenant.auth0.com) and AUTH0_AUDIENCE (your-api-identifier). 3. Install @mastra/auth-auth0@latest using npm/pnpm/yarn/bun. 4. Import MastraAuthAuth0 from @mastra/auth-auth0. 5. Configure in Mastra options: new MastraAuthAuth0() or with custom options including domain, audience, and optional authorizeUser function. 6. For client apps, install @auth0/auth0-react and wrap app with Auth0Provider using REACT_APP_AUTH0_DOMAIN, REACT_APP_AUTH0_CLIENT_ID, and REACT_APP_AUTH0_AUDIENCE. 7. Retrieve access tokens using getAccessTokenSilently() hook. 8. Configure MastraClient with baseUrl and headers containing Authorization: ‘Bearer ‘. 9. Include the Bearer token in all API requests to authenticated endpoints.

Kết quả

Auth0-issued JWT tokens are verified for signature, expiration, audience, and issuer. Valid tokens allow authenticated access to Mastra resources. The authorizeUser function enables custom authorization logic based on user properties like email.

Điều kiện áp dụng

Requires @mastra/core for Mastra setup and @mastra/client-js for client-side API calls. Works with any Auth0-configured API audience.


Nội dung gốc (Original)

Auth0

The @mastra/auth-auth0 package provides authentication for Mastra using Auth0. It verifies incoming requests using Auth0-issued JWT tokens and integrates with the Mastra server using the auth option.

Prerequisites

This example uses Auth0 authentication. Make sure to:

  1. Create an Auth0 account at auth0.com
  2. Set up an Application in your Auth0 Dashboard
  3. Configure an API in your Auth0 Dashboard with an identifier (audience)
  4. Configure your application’s allowed callback URLs, web origins, and logout URLs
AUTH0_DOMAIN=your-tenant.auth0.com
AUTH0_AUDIENCE=your-api-identifier

Note: You can find your domain in the Auth0 Dashboard under Applications > Settings. The audience is the identifier of your API configured in Auth0 Dashboard > APIs.

For detailed setup instructions, refer to the Auth0 quickstarts for your specific platform.

Installation

Before you can use the MastraAuthAuth0 class you have to install the @mastra/auth-auth0 package.

npm:

npm install @mastra/auth-auth0@latest

pnpm:

pnpm add @mastra/auth-auth0@latest

Yarn:

yarn add @mastra/auth-auth0@latest

Bun:

bun add @mastra/auth-auth0@latest

Usage examples

Basic usage with environment variables

import { Mastra } from '@mastra/core'
import { MastraAuthAuth0 } from '@mastra/auth-auth0'
 
export const mastra = new Mastra({
  server: {
    auth: new MastraAuthAuth0(),
  },
})

Custom configuration

import { Mastra } from '@mastra/core'
import { MastraAuthAuth0 } from '@mastra/auth-auth0'
 
export const mastra = new Mastra({
  server: {
    auth: new MastraAuthAuth0({
      domain: process.env.AUTH0_DOMAIN,
      audience: process.env.AUTH0_AUDIENCE,
    }),
  },
})

Configuration

User Authorization

By default, MastraAuthAuth0 allows all authenticated users who have valid Auth0 tokens for the specified audience. The token verification ensures that:

  1. The token is properly signed by Auth0
  2. The token isn’t expired
  3. The token audience matches your configured audience
  4. The token issuer matches your Auth0 domain

To customize user authorization, provide a custom authorizeUser function:

import { MastraAuthAuth0 } from '@mastra/auth-auth0'
 
const auth0Provider = new MastraAuthAuth0({
  authorizeUser: async user => {
    // Custom authorization logic
    return user.email?.endsWith('@yourcompany.com') || false
  },
})

Info: Visit MastraAuthAuth0 for all available configuration options.

Client-side setup

When using Auth0 auth, you’ll need to set up the Auth0 React SDK, authenticate users, and retrieve their access tokens to pass to your Mastra requests.

Setting up Auth0 React SDK

First, install and configure the Auth0 React SDK in your application:

npm:

npm install @auth0/auth0-react

pnpm:

pnpm add @auth0/auth0-react

Yarn:

yarn add @auth0/auth0-react

Bun:

bun add @auth0/auth0-react
import React from 'react'
import { Auth0Provider } from '@auth0/auth0-react'
 
const Auth0ProviderWithHistory = ({ children }) => {
  return (
    <Auth0Provider
      domain={process.env.REACT_APP_AUTH0_DOMAIN}
      clientId={process.env.REACT_APP_AUTH0_CLIENT_ID}
      authorizationParams={{
        redirect_uri: window.location.origin,
        audience: process.env.REACT_APP_AUTH0_AUDIENCE,
        scope: 'read:current_user update:current_user_metadata',
      }}
    >
      {children}
    </Auth0Provider>
  )
}
 
export default Auth0ProviderWithHistory

Retrieving access tokens

Use the Auth0 React SDK to authenticate users and retrieve their access tokens:

import { useAuth0 } from '@auth0/auth0-react'
 
export const useAuth0Token = () => {
  const { getAccessTokenSilently } = useAuth0()
 
  const getAccessToken = async () => {
    const token = await getAccessTokenSilently()
    return token
  }
 
  return { getAccessToken }
}

Note: Refer to the Auth0 React SDK documentation for more authentication methods and configuration options.

Configuring MastraClient

When auth is enabled, all requests made with MastraClient must include a valid Auth0 access token in the Authorization header:

import { MastraClient } from '@mastra/client-js'
 
export const createMastraClient = (accessToken: string) => {
  return new MastraClient({
    baseUrl: 'https://<mastra-api-url>',
    headers: {
      Authorization: `Bearer ${accessToken}`,
    },
  })
}

Info: The access token must be prefixed with Bearer in the Authorization header.

Visit Mastra Client SDK for more configuration options.

Making authenticated requests

Once MastraClient is configured with the Auth0 access token, you can send authenticated requests:

React:

import React, { useState } from 'react'
import { useAuth0 } from '@auth0/auth0-react'
import { MastraClient } from '@mastra/client-js'
 
export const MastraApiTest = () => {
  const { getAccessTokenSilently } = useAuth0()
  const [result, setResult] = useState(null)
 
  const callMastraApi = async () => {
    const token = await getAccessTokenSilently()
 
    const mastra = new MastraClient({
      baseUrl: 'http://localhost:4111',
      headers: {
        Authorization: `Bearer ${token}`,
      },
    })
 
    const weatherAgent = mastra.getAgent('weatherAgent')
    const response = await weatherAgent.generate("What's the weather like in New York")
 
    setResult(response.text)
  }
 
  return (
    <div>
      <button onClick={callMastraApi}>Test Mastra API</button>
 
      {result && (
        <div className="result">
          <h6>Result:</h6>
          <pre>{result}</pre>
        </div>
      )}
    </div>
  )
}

cURL:

curl -X POST http://localhost:4111/api/agents/weatherAgent/generate \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer <your-auth0-access-token>" \
  -d '{
    "messages": "Weather in London"
  }'

Liên kết

Xem thêm: