Skip to main content

MastraAuthAuth0 类

🌐 MastraAuthAuth0 Class

MastraAuthAuth0 类为 Mastra 提供使用 Auth0 的身份验证。它使用 Auth0 签发的 JWT 令牌验证传入请求,并通过 auth 选项与 Mastra 服务器集成。

🌐 The MastraAuthAuth0 class 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.

先决条件
Direct link to 先决条件

🌐 Prerequisites

此示例使用 Auth0 进行身份验证。请确保:

🌐 This example uses Auth0 authentication. Make sure to:

  1. auth0.com 创建一个 Auth0 账户
  2. 在你的 Auth0 控制台中设置应用
  3. 在你的 Auth0 仪表板中配置一个带有标识符(受众)的 API
  4. 配置应用允许的回调 URL、网页来源和登出 URL
.env
AUTH0_DOMAIN=your-tenant.auth0.com
AUTH0_AUDIENCE=your-api-identifier
note

你可以在 Auth0 仪表板的 应用 > 设置 中找到你的域名。受众是你在 Auth0 仪表板 > API 中配置的 API 的标识符。

🌐 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.

有关详细的设置说明,请参阅适用于你特定平台的 Auth0 快速入门

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

安装
Direct link to 安装

🌐 Installation

在使用 MastraAuthAuth0 类之前,你必须先安装 @mastra/auth-auth0 包。

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

npm install @mastra/auth-auth0@latest

用法示例
Direct link to 用法示例

🌐 Usage examples

使用环境变量的基本用法
Direct link to 使用环境变量的基本用法

🌐 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(),
},
});

自定义配置
Direct link to 自定义配置

🌐 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,
}),
},
});

配置
Direct link to 配置

🌐 Configuration

用户授权
Direct link to 用户授权

🌐 User Authorization

默认情况下,MastraAuthAuth0 允许所有拥有指定受众有效 Auth0 令牌的经过身份验证的用户访问。令牌验证确保以下内容:

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

  1. 该令牌已由 Auth0 正确签名
  2. 令牌未过期
  3. 令牌的受众与你配置的受众匹配
  4. 令牌发行者与你的 Auth0 域匹配

要自定义用户权限,请提供一个自定义的 authorizeUser 函数:

🌐 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;
},
});
info

访问 MastraAuthAuth0 了解所有可用的配置选项。

🌐 Visit MastraAuthAuth0 for all available configuration options.

客户端设置
Direct link to 客户端设置

🌐 Client-side setup

在使用 Auth0 身份验证时,你需要设置 Auth0 React SDK、验证用户身份,并获取他们的访问令牌以传递给你的 Mastra 请求。

🌐 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.

设置 Auth0 React SDK
Direct link to 设置 Auth0 React SDK

🌐 Setting up Auth0 React SDK

首先,在你的应用中安装并配置 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;

正在获取访问令牌
Direct link to 正在获取访问令牌

🌐 Retrieving access tokens

使用 Auth0 React SDK 验证用户身份并获取他们的访问令牌:

🌐 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 };
};
note

有关更多身份验证方法和配置选项,请参考 Auth0 React SDK 文档

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

配置 MastraClient
Direct link to configuring-mastraclient

🌐 Configuring MastraClient

当启用 auth 时,所有使用 MastraClient 发出的请求必须在 Authorization 请求头中包含有效的 Auth0 访问令牌:

🌐 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}`,
},
});
};
info

访问令牌在 Authorization 头中必须以 Bearer 为前缀。

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

访问 Mastra Client SDK 以获取更多配置选项。

🌐 Visit Mastra Client SDK for more configuration options.

进行身份验证的请求
Direct link to 进行身份验证的请求

🌐 Making authenticated requests

一旦使用 Auth0 访问令牌配置了 MastraClient,你就可以发送经过身份验证的请求:

🌐 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>
);
};