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
- pnpm
- Yarn
- Bun
npm install @mastra/auth-clerk@latest
pnpm add @mastra/auth-clerk@latest
yarn add @mastra/auth-clerk@latest
bun add @mastra/auth-clerk@latest
使用範例使用範例 的直接連結
src/mastra/index.ts
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,了解所有可用的設定選項。
客戶端設定客戶端設定 的直接連結
使用 Clerk 身份驗證時,你需要在客戶端從 Clerk 取得存取權杖,並將其傳遞至 Mastra 請求。
取得存取權杖取得存取權杖 的直接連結
使用 Clerk React hooks 驗證用戶身份並取得其存取權杖:
lib/auth.ts
import { useAuth } from '@clerk/nextjs'
export const useClerkAuth = () => {
const { getToken } = useAuth()
const getAccessToken = async () => {
const token = await getToken()
return token
}
return { getAccessToken }
}
詳情請參閱 Clerk 文檔。
設定 MastraClientconfiguring-mastraclient 的直接連結
啟用 auth 後,所有透過 MastraClient 發出的請求都必須在 Authorization header 中包含有效的 Clerk 存取權杖:
lib/mastra/mastra-client.ts
import { MastraClient } from '@mastra/client-js'
export const mastraClient = new MastraClient({
baseUrl: 'https://<mastra-api-url>',
headers: {
Authorization: `Bearer ${accessToken}`,
},
})
資訊
在 Authorization header 中,存取權杖前必須加上 Bearer。
請參閱 Mastra Client SDK,了解更多設定選項。
發出已通過身份驗證的請求發出已通過身份驗證的請求 的直接連結
使用 Clerk 存取權杖設定 MastraClient 後,便可以發出已通過身份驗證的請求:
- React
- cURL
src/components/test-agent.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 <button onClick={handleClick}>Test Agent</button>
}
curl -X POST http://localhost:4111/api/agents/weatherAgent/generate \
-H "Content-Type: application/json" \
-H "Authorization: Bearer <your-clerk-access-token>" \
-d '{
"messages": "Weather in London"
}'