> Discover all available pages from the documentation index: https://mastra.zisheng.pro/llms.txt # WorkOS `@mastra/auth-workos` 包使用 WorkOS 为 Mastra 提供身份验证。它使用 WorkOS 访问令牌验证传入请求,并通过 `auth` 选项与 Mastra 服务器集成。 ## 前置条件 本示例使用 WorkOS 身份验证。请确保: 1. 在 [workos.com](https://workos.com/) 创建 WorkOS 账户 2. 在 WorkOS Dashboard 中设置 Application 3. 配置重定向 URI 和允许的来源 4. 设置 Organization,并根据需要配置用户角色 ```env WORKOS_API_KEY=sk_live_... WORKOS_CLIENT_ID=client_... ``` > **备注:** 可以分别在 WorkOS Dashboard 的 API Keys 和 Applications 下找到 API 密钥和 Client ID。 > > 有关详细设置说明,请参阅适用于相应平台的 [WorkOS 文档](https://workos.com/docs)。 ## 安装 在使用 `MastraAuthWorkos` 类之前,必须安装 `@mastra/auth-workos` 包。 **npm**: ```bash npm install @mastra/auth-workos@latest ``` **pnpm**: ```bash pnpm add @mastra/auth-workos@latest ``` **Yarn**: ```bash yarn add @mastra/auth-workos@latest ``` **Bun**: ```bash bun add @mastra/auth-workos@latest ``` ## 用法示例 ### 使用环境变量的基本用法 ```typescript import { Mastra } from '@mastra/core' import { MastraAuthWorkos } from '@mastra/auth-workos' export const mastra = new Mastra({ server: { auth: new MastraAuthWorkos(), }, }) ``` ### 自定义配置 ```typescript import { Mastra } from '@mastra/core' import { MastraAuthWorkos } from '@mastra/auth-workos' export const mastra = new Mastra({ server: { auth: new MastraAuthWorkos({ apiKey: process.env.WORKOS_API_KEY, clientId: process.env.WORKOS_CLIENT_ID, }), }, }) ``` ## 配置 ### 默认授权 默认情况下,`MastraAuthWorkos` 允许任何已通过身份验证的 WorkOS 用户访问。当解析出的用户对象同时包含 Mastra 用户 ID 和 WorkOS 用户 ID 时,授权检查成功。 ### 加载 FGA 成员资格 使用 [`MastraFGAWorkos`](https://mastra.zisheng.pro/docs/server/auth/fga) 时,请设置 `fetchMemberships: true`。这会让身份验证 Provider 在身份验证期间加载用户的 WorkOS Organization 成员资格,使 FGA 检查能够解析正确的 Organization 成员资格 ID。 ```typescript import { MastraAuthWorkos, MastraFGAWorkos } from '@mastra/auth-workos' const workosAuth = new MastraAuthWorkos({ apiKey: process.env.WORKOS_API_KEY, clientId: process.env.WORKOS_CLIENT_ID, fetchMemberships: true, }) const workosFga = new MastraFGAWorkos({ apiKey: process.env.WORKOS_API_KEY, clientId: process.env.WORKOS_CLIENT_ID, }) ``` 当 `fetchMemberships` 为 `false` 时,Mastra 会跳过每个已认证请求中的额外 WorkOS `listOrganizationMemberships()` 调用。 ### 服务令牌和自定义 JWT 模板 对于机器到机器或服务账户访问,可以配置 `MastraAuthWorkos`,使其信任来自 WorkOS 自定义 JWT 模板的已验证 bearer-token claim。 ```typescript import { MastraAuthWorkos } from '@mastra/auth-workos' const workosAuth = new MastraAuthWorkos({ apiKey: process.env.WORKOS_API_KEY, clientId: process.env.WORKOS_CLIENT_ID, redirectUri: process.env.WORKOS_REDIRECT_URI, trustJwtClaims: true, jwtClaims: { organizationId: 'org_id', organizationMembershipId: 'urn:mastra:organization_membership_id', }, }) ``` 当 JWT 模板已包含 Mastra 所需的准确 FGA 上下文(例如 `organizationMembershipId`、租户 ID 或服务主体标识符)时,此功能很有用。启用 `trustJwtClaims` 后,如果 bearer 令牌不应通过 `workos.userManagement.getUser()` 往返处理,Mastra 可以回退到这些已验证 claim。 ### 自定义授权 如果需要更严格的授权,请继承 `MastraAuthWorkos` 并覆盖 `authorizeUser()`: ```typescript import { MastraAuthWorkos } from '@mastra/auth-workos' import type { HonoRequest } from 'hono' class AdminOnlyWorkosAuth extends MastraAuthWorkos { async authorizeUser(user: any, _request: HonoRequest): Promise { return user?.metadata?.role === 'admin' } } const workosAuth = new AdminOnlyWorkosAuth({ apiKey: process.env.WORKOS_API_KEY, clientId: process.env.WORKOS_CLIENT_ID, }) ``` 有关所有可用配置选项,请参阅 [MastraAuthWorkos](https://mastra.zisheng.pro/reference/auth/workos)。 ## 客户端设置 使用 WorkOS 身份验证时,需要实现 WorkOS 身份验证流程,将授权码交换为访问令牌,然后在 Mastra 请求中使用该令牌。 ### 安装 WorkOS SDK 首先,在应用中安装 WorkOS SDK: **npm**: ```bash npm install @workos-inc/node ``` **pnpm**: ```bash pnpm add @workos-inc/node ``` **Yarn**: ```bash yarn add @workos-inc/node ``` **Bun**: ```bash bun add @workos-inc/node ``` ### 将代码交换为访问令牌 用户完成 WorkOS 身份验证流程并携带授权码返回后,请将授权码交换为访问令牌: ```typescript import { WorkOS } from '@workos-inc/node' const workos = new WorkOS(process.env.WORKOS_API_KEY) export const authenticateWithWorkos = async (code: string, clientId: string) => { const authenticationResponse = await workos.userManagement.authenticateWithCode({ code, clientId, }) return authenticationResponse.accessToken } ``` > **备注:** 有关更多身份验证方法和配置选项,请参阅 [WorkOS User Management 文档](https://workos.com/docs/authkit/vanilla/nodejs)。 ## 配置 `MastraClient` 启用 `auth` 后,使用 `MastraClient` 发出的所有请求都必须在 `Authorization` 标头中包含有效的 WorkOS 访问令牌: ```typescript import { MastraClient } from '@mastra/client-js' export const createMastraClient = (accessToken: string) => { return new MastraClient({ baseUrl: 'https://', headers: { Authorization: `Bearer ${accessToken}`, }, }) } ``` > **信息:** 访问令牌在 Authorization 标头中必须带有 `Bearer` 前缀。 > > 有关更多配置选项,请参阅 [Mastra Client SDK](https://mastra.zisheng.pro/docs/server/mastra-client)。 ### 发出经过身份验证的请求 使用 WorkOS 访问令牌配置 `MastraClient` 后,即可发送经过身份验证的请求: **React**: ```typescript import { WorkOS } from '@workos-inc/node' import { MastraClient } from '@mastra/client-js' const workos = new WorkOS(process.env.WORKOS_API_KEY) export const callMastraWithWorkos = async (code: string, clientId: string) => { const authenticationResponse = await workos.userManagement.authenticateWithCode({ code, clientId, }) const token = authenticationResponse.accessToken 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 Nairobi") return response.text } ``` **cURL**: ```bash curl -X POST http://localhost:4111/api/agents/weatherAgent/generate \ -H "Content-Type: application/json" \ -H "Authorization: Bearer " \ -d '{ "messages": "Weather in London" }' ```