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 文檔。
設定 MastraClientconfiguring-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}`,
},
})
}
在 Authorization header 中,access token 前面必須加上 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"
}'