Auth0
@mastra/auth-auth0 套件透過 Auth0 為 Mastra 提供驗證功能。它會使用 Auth0 核發的 JWT token 驗證傳入的請求,並透過 auth 選項與 Mastra 伺服器整合。
事前準備「事前準備」的直接連結
此範例使用 Auth0 驗證。請務必完成下列事項:
- 在 auth0.com 建立 Auth0 帳號
- 在 Auth0 Dashboard 中設定 Application
- 在 Auth0 Dashboard 中設定 API 及其識別碼(audience)
- 設定應用程式允許的 callback URL、web origin 與 logout URL
AUTH0_DOMAIN=your-tenant.auth0.com
AUTH0_AUDIENCE=your-api-identifier
你可以在 Auth0 Dashboard 的 Applications > Settings 中找到 domain。Audience 是在 Auth0 Dashboard > APIs 中設定的 API 識別碼。
如需詳細設定指示,請參閱適用於你所用平台的 Auth0 快速入門。
安裝「安裝」的直接連結
使用 MastraAuthAuth0 類別前,必須先安裝 @mastra/auth-auth0 套件。
- npm
- pnpm
- Yarn
- Bun
npm install @mastra/auth-auth0@latest
pnpm add @mastra/auth-auth0@latest
yarn add @mastra/auth-auth0@latest
bun add @mastra/auth-auth0@latest
使用範例「使用範例」的直接連結
搭配環境變數的基本用法「搭配環境變數的基本用法」的直接連結
import { Mastra } from '@mastra/core'
import { MastraAuthAuth0 } from '@mastra/auth-auth0'
export const mastra = new Mastra({
server: {
auth: new MastraAuthAuth0(),
},
})
自訂設定「自訂設定」的直接連結
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,
}),
},
})
設定「設定」的直接連結
使用者授權「使用者授權」的直接連結
MastraAuthAuth0 預設允許所有持有指定 audience 之有效 Auth0 token 的已驗證使用者。Token 驗證會確保:
- Token 已由 Auth0 正確簽署
- Token 尚未過期
- Token audience 與你設定的 audience 相符
- Token issuer 與你的 Auth0 domain 相符
若要自訂使用者授權,請提供自訂的 authorizeUser 函式:
import { MastraAuthAuth0 } from '@mastra/auth-auth0'
const auth0Provider = new MastraAuthAuth0({
authorizeUser: async user => {
// Custom authorization logic
return user.email?.endsWith('@yourcompany.com') || false
},
})
請參閱 MastraAuthAuth0,瞭解所有可用的設定選項。
用戶端設定「用戶端設定」的直接連結
使用 Auth0 驗證時,你需要設定 Auth0 React SDK、驗證使用者,並取得其 access token 以傳入 Mastra 請求。
設定 Auth0 React SDK「設定 Auth0 React SDK」的直接連結
首先,在應用程式中安裝並設定 Auth0 React SDK:
- npm
- pnpm
- Yarn
- Bun
npm install @auth0/auth0-react
pnpm add @auth0/auth0-react
yarn add @auth0/auth0-react
bun add @auth0/auth0-react
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
取得 access token「取得 access token」的直接連結
使用 Auth0 React SDK 驗證使用者並取得其 access token:
import { useAuth0 } from '@auth0/auth0-react'
export const useAuth0Token = () => {
const { getAccessTokenSilently } = useAuth0()
const getAccessToken = async () => {
const token = await getAccessTokenSilently()
return token
}
return { getAccessToken }
}
如需更多驗證方式與設定選項,請參閱 Auth0 React SDK 文件。
設定 MastraClient「configuring-mastraclient」的直接連結
啟用 auth 後,所有透過 MastraClient 發出的請求都必須在 Authorization header 中包含有效的 Auth0 access token:
import { MastraClient } from '@mastra/client-js'
export const createMastraClient = (accessToken: string) => {
return new MastraClient({
baseUrl: 'https://<mastra-api-url>',
headers: {
Authorization: `Bearer ${accessToken}`,
},
})
}
Access token 在 Authorization header 中必須以 Bearer 為前綴。
如需更多設定選項,請參閱 Mastra Client SDK。
發出已驗證的請求「發出已驗證的請求」的直接連結
使用 Auth0 access token 設定 MastraClient 後,即可傳送已驗證的請求:
- React
- cURL
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>
)
}
curl -X POST http://localhost:4111/api/agents/weatherAgent/generate \
-H "Content-Type: application/json" \
-H "Authorization: Bearer <your-auth0-access-token>" \
-d '{
"messages": "Weather in London"
}'