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 文件。
設定 MastraClient「configuring-mastraclient」的直接連結
啟用 auth 後,透過 MastraClient 發出的所有請求都必須在 Authorization 標頭中包含有效的 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 標頭中必須加上 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"
}'