跳至主要內容

Google

@mastra/auth-google 依賴套件使用 Google Workspace,為 Mastra 提供身份驗證和以角色為基礎的存取控制。它支援使用加密工作階段 Cookie 的 OAuth 2.0/OIDC 登入流程、驗證 Google ID token,並將 Google Workspace 群組映射至 Mastra 權限。

當 Studio 使用者透過 Google 登入,而存取權應限制於一個或多個 Google Workspace 網域時,便可使用此依賴套件。

先決條件
先決條件 的直接連結

本指南使用 Google Workspace 身份驗證。請確保完成以下設定:

  1. 建立或選擇 Google Cloud 項目
  2. 為網絡應用程式設定 OAuth 用戶端
  3. 將 Mastra SSO 回呼 URL 加入已授權的重新導向 URI
  4. 如計劃使用 RBAC,請設定 Google Workspace 群組

如要使用 Google Groups RBAC,亦請設定具備全網域委派的 Google Workspace 服務帳戶,並向其授予 Directory API 唯讀群組範圍:

https://www.googleapis.com/auth/admin.directory.group.readonly

請確保已設定環境變數。

.env
GOOGLE_CLIENT_ID=your-client-id.apps.googleusercontent.com
GOOGLE_CLIENT_SECRET=your-client-secret
GOOGLE_REDIRECT_URI=http://localhost:4111/api/auth/sso/callback
GOOGLE_COOKIE_PASSWORD=a-random-string-at-least-32-characters-long
GOOGLE_ALLOWED_DOMAINS=example.com

GOOGLE_SERVICE_ACCOUNT_EMAIL=service-account@project.iam.gserviceaccount.com
GOOGLE_SERVICE_ACCOUNT_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----\n"
GOOGLE_WORKSPACE_ADMIN_EMAIL=admin@example.com
備註

GOOGLE_COOKIE_PASSWORD 會加密工作階段 Cookie。如省略此變數,系統會使用自動產生的值,但該值不會在伺服器重新啟動後保留。請為生產環境明確設定此變數。

MastraAuthGoogle 會自動讀取 GOOGLE_* 身份驗證變數。上述服務帳戶變數則由你傳遞至 MastraRBACGoogle 的設定程式碼讀取。

安裝
安裝 的直接連結

使用 MastraAuthGoogle 類別前,請先安裝 @mastra/auth-google 依賴套件。

npm install @mastra/auth-google

使用範例
使用範例 的直接連結

配合環境變數的基本用法
配合環境變數的基本用法 的直接連結

設定上述環境變數後,所有建構函式參數均為選填:

src/mastra/index.ts
import { Mastra } from '@mastra/core'
import { MastraAuthGoogle } from '@mastra/auth-google'

export const mastra = new Mastra({
server: {
auth: new MastraAuthGoogle(),
},
})
注意

使用 allowedDomainsGOOGLE_ALLOWED_DOMAINS 強制限制 Workspace 存取權。Mastra 會檢查經 Google 驗證的 hd claim,而非電郵地址的後綴。

自訂設定
自訂設定 的直接連結

如不想依賴環境變數,可直接傳遞建構函式選項:

src/mastra/index.ts
import { Mastra } from '@mastra/core'
import { MastraAuthGoogle } from '@mastra/auth-google'

export const mastra = new Mastra({
server: {
auth: new MastraAuthGoogle({
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
redirectUri: process.env.GOOGLE_REDIRECT_URI,
allowedDomains: ['example.com'],
}),
},
})

配合 Google Groups RBAC 的身份驗證
配合 Google Groups RBAC 的身份驗證 的直接連結

加入 MastraRBACGoogle,將 Google Workspace 群組映射至 Mastra 權限:

src/mastra/index.ts
import { Mastra } from '@mastra/core'
import { MastraAuthGoogle, MastraRBACGoogle } from '@mastra/auth-google'

export const mastra = new Mastra({
server: {
auth: new MastraAuthGoogle(),
rbac: new MastraRBACGoogle({
serviceAccount: {
clientEmail: process.env.GOOGLE_SERVICE_ACCOUNT_EMAIL!,
privateKey: process.env.GOOGLE_SERVICE_ACCOUNT_PRIVATE_KEY!,
subject: process.env.GOOGLE_WORKSPACE_ADMIN_EMAIL!,
},
roleMapping: {
'admins@example.com': ['*'],
'engineering@example.com': ['agents:*', 'workflows:*', 'tools:*'],
'viewers@example.com': ['agents:read', 'workflows:read'],
_default: [], // users with unmapped groups get no permissions
},
}),
},
})

跨 Provider 用法
跨 Provider 用法 的直接連結

使用另一個身份驗證 Provider(Auth0、Clerk 等)登入,並使用 Google Workspace 群組進行 RBAC。傳遞 getUserKey 函式,從其他 Provider 的使用者物件解析 Google Directory API 使用者金鑰:

src/mastra/index.ts
import { Mastra } from '@mastra/core'
import { MastraAuthAuth0 } from '@mastra/auth-auth0'
import { MastraRBACGoogle } from '@mastra/auth-google'

export const mastra = new Mastra({
server: {
auth: new MastraAuthAuth0(),
rbac: new MastraRBACGoogle({
getUserKey: user => {
if (!user || typeof user !== 'object') return undefined

const { email } = user as { email?: unknown }
return typeof email === 'string' ? email : undefined
},
serviceAccount: {
clientEmail: process.env.GOOGLE_SERVICE_ACCOUNT_EMAIL!,
privateKey: process.env.GOOGLE_SERVICE_ACCOUNT_PRIVATE_KEY!,
subject: process.env.GOOGLE_WORKSPACE_ADMIN_EMAIL!,
},
roleMapping: {
'engineering@example.com': ['agents:*', 'workflows:*'],
'admins@example.com': ['*'],
_default: [],
},
}),
},
})

如要了解所有可用設定選項,請參閱 MastraAuthGoogle

角色映射
角色映射 的直接連結

roleMapping 選項會將 Google Workspace 群組電郵地址映射至 Mastra 權限字串陣列。權限採用 resource:action 模式,並支援萬用字元:

const rbac = new MastraRBACGoogle({
roleMapping: {
// full access to everything
'admins@example.com': ['*'],

// full access to agents and workflows
'engineering@example.com': ['agents:*', 'workflows:*'],

// read-only access
'viewers@example.com': ['agents:read', 'workflows:read'],

// users whose groups don't match any key above
_default: [],
},
})

預設會使用群組電郵地址作為角色 ID。如想按群組名稱或其他屬性映射,請使用 mapGroupToRoles_default key 會向 Google Workspace 群組不符合任何其他 key 的使用者指派權限。

用戶端設定
用戶端設定 的直接連結

啟用身份驗證後,向 Mastra 路由發出的請求均須經過身份驗證。使用 GOOGLE_CLIENT_SECRET 啟用 SSO 後,MastraAuthGoogle 會使用 Google 登入,並在登入後設定加密的工作階段 Cookie。

對於跨來源請求(例如位於 :3000 的前端呼叫位於 :4111 的 Mastra),請在 Mastra 伺服器上啟用 CORS 憑證:

src/mastra/index.ts
export const mastra = new Mastra({
server: {
auth: new MastraAuthGoogle(),
cors: {
origin: 'http://localhost:3000',
credentials: true,
},
},
})

設定用戶端以包含憑證:

lib/mastra-client.ts
import { MastraClient } from '@mastra/client-js'

export const mastraClient = new MastraClient({
baseUrl: 'http://localhost:4111',
credentials: 'include',
})

Bearer token
Bearer token 的直接連結

你亦可將 Google ID token 作為 Bearer token 傳遞。Mastra 會使用 Google 的 JSON Web Key Set(JWKS)端點驗證 token:

lib/mastra-client.ts
import { MastraClient } from '@mastra/client-js'

export const createMastraClient = (idToken: string) => {
return new MastraClient({
baseUrl: 'http://localhost:4111',
headers: {
Authorization: `Bearer ${idToken}`,
},
})
}

如要了解更多設定選項,請參閱 Mastra Client SDK

發出已驗證身份的請求
發出已驗證身份的請求 的直接連結

src/api/agents.ts
import { mastraClient } from '../lib/mastra-client'

const agent = mastraClient.getAgent('weatherAgent')
const response = await agent.generate('Weather in London')
console.log(response)

疑難排解
疑難排解 的直接連結

  • 登入後出現 401:檢查 GOOGLE_CLIENT_IDGOOGLE_CLIENT_SECRETGOOGLE_REDIRECT_URI 是否與 Google Cloud OAuth 用戶端相符。
  • Workspace 使用者遭拒絕:確認 GOOGLE_ALLOWED_DOMAINS 與 Google ID token 的 hd claim 相符。
  • 一般 Gmail 帳戶遭拒絕:設定 allowedDomains 後出現此情況屬預期行為,因為 Gmail 帳戶沒有 Workspace hd claim。
  • RBAC 傳回預設權限:系統未能為使用者解析任何角色。請確認使用者電郵或自訂 getUserKey、Google 群組成員資格及 roleMapping。如 Directory API 查詢失敗,Provider 會擲回錯誤,而非傳回 _default
  • Cookie 未隨跨來源請求傳送:在 MastraClient 中設定 credentials: "include",並使用前端來源和 credentials: true 設定 server.cors
  • 重新啟動後工作階段遺失:將 GOOGLE_COOKIE_PASSWORD 設為至少 32 個字元的固定值。如未設定,開發環境會使用自動產生的金鑰,並在每次重新啟動時變更。