跳到主要内容
非官方简体中文翻译,内容版权归 Mastra 所有,遵循 Apache-2.0 许可。

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
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
.env
AUTH0_DOMAIN=your-tenant.auth0.com
AUTH0_AUDIENCE=your-api-identifier
备注

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
Installation的直接链接

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

npm install @mastra/auth-auth0@latest

Usage examples
Usage examples的直接链接

Basic usage with environment variables
Basic usage with environment variables的直接链接

src/mastra/index.ts
import { Mastra } from '@mastra/core'
import { MastraAuthAuth0 } from '@mastra/auth-auth0'

export const mastra = new Mastra({
server: {
auth: new MastraAuthAuth0(),
},
})

Custom configuration
Custom configuration的直接链接

src/mastra/index.ts
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
Configuration的直接链接

User Authorization
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:

src/mastra/auth.ts
import { MastraAuthAuth0 } from '@mastra/auth-auth0'

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

Visit MastraAuthAuth0 for all available configuration options.

Client-side setup
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
Setting up Auth0 React SDK的直接链接

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

npm install @auth0/auth0-react
src/auth0-provider.tsx
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
Retrieving access tokens的直接链接

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

lib/auth.ts
import { useAuth0 } from '@auth0/auth0-react'

export const useAuth0Token = () => {
const { getAccessTokenSilently } = useAuth0()

const getAccessToken = async () => {
const token = await getAccessTokenSilently()
return token
}

return { getAccessToken }
}
备注

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

Configuring MastraClient
configuring-mastraclient的直接链接

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

lib/mastra/mastra-client.ts
import { MastraClient } from '@mastra/client-js'

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

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

Visit Mastra Client SDK for more configuration options.

Making authenticated requests
Making authenticated requests的直接链接

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

src/components/mastra-api-test.tsx
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>
)
}