> Discover all available pages from the documentation index: https://mastra.zisheng.pro/zh-HK/llms.txt # Clerk `@mastra/auth-clerk` 依賴套件透過 Clerk 為 Mastra 提供身份驗證。它使用 Clerk 的身份驗證系統來驗證傳入的請求,並透過 `auth` 選項與 Mastra 伺服器整合。 ## 前置要求 此範例使用 Clerk 身份驗證。請確保已將 Clerk 憑證加入 `.env` 文件,並已正確設定 Clerk 項目。 ```env CLERK_PUBLISHABLE_KEY=pk_test_... CLERK_SECRET_KEY=sk_test_... CLERK_JWKS_URI=https://your-clerk-domain.clerk.accounts.dev/.well-known/jwks.json ``` > **備註:** 你可以在 Clerk Dashboard 的「API Keys」下找到這些金鑰。 ## 安裝 使用 `MastraAuthClerk` 類別前,必須先安裝 `@mastra/auth-clerk` 依賴套件。 **npm**: ```bash npm install @mastra/auth-clerk@latest ``` **pnpm**: ```bash pnpm add @mastra/auth-clerk@latest ``` **Yarn**: ```bash yarn add @mastra/auth-clerk@latest ``` **Bun**: ```bash bun add @mastra/auth-clerk@latest ``` ## 使用範例 ```typescript import { Mastra } from '@mastra/core' import { MastraAuthClerk } from '@mastra/auth-clerk' export const mastra = new Mastra({ server: { auth: new MastraAuthClerk({ publishableKey: process.env.CLERK_PUBLISHABLE_KEY, secretKey: process.env.CLERK_SECRET_KEY, jwksUri: process.env.CLERK_JWKS_URI, }), }, }) ``` > **資訊:** 預設的 `authorizeUser` 方法允許所有已通過身份驗證的用戶。如要自訂用戶授權,請在建立 Provider 時提供自訂的 `authorizeUser` 函數。 > > 請參閱 [MastraAuthClerk](https://mastra.zisheng.pro/zh-HK/reference/auth/clerk),了解所有可用的設定選項。 ## 客戶端設定 使用 Clerk 身份驗證時,你需要在客戶端從 Clerk 取得存取權杖,並將其傳遞至 Mastra 請求。 ### 取得存取權杖 使用 Clerk React hooks 驗證用戶身份並取得其存取權杖: ```typescript import { useAuth } from '@clerk/nextjs' export const useClerkAuth = () => { const { getToken } = useAuth() const getAccessToken = async () => { const token = await getToken() return token } return { getAccessToken } } ``` 詳情請參閱 [Clerk 文檔](https://clerk.com/docs)。 ## 設定 `MastraClient` 啟用 `auth` 後,所有透過 `MastraClient` 發出的請求都必須在 `Authorization` header 中包含有效的 Clerk 存取權杖: ```typescript import { MastraClient } from '@mastra/client-js' export const mastraClient = new MastraClient({ baseUrl: 'https://', headers: { Authorization: `Bearer ${accessToken}`, }, }) ``` > **資訊:** 在 Authorization header 中,存取權杖前必須加上 `Bearer`。 > > 請參閱 [Mastra Client SDK](https://mastra.zisheng.pro/zh-HK/docs/server/mastra-client),了解更多設定選項。 ### 發出已通過身份驗證的請求 使用 Clerk 存取權杖設定 `MastraClient` 後,便可以發出已通過身份驗證的請求: **React**: ```tsx 'use client' import { useAuth } from '@clerk/nextjs' import { MastraClient } from '@mastra/client-js' export const TestAgent = () => { const { getToken } = useAuth() async function handleClick() { const token = await getToken() const client = new MastraClient({ baseUrl: 'http://localhost:4111', headers: token ? { Authorization: `Bearer ${token}` } : undefined, }) const weatherAgent = client.getAgent('weatherAgent') const response = await weatherAgent.generate("What's the weather like in New York") console.log({ response }) } return } ``` **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" }' ```