> Discover all available pages from the documentation index: https://mastra.zisheng.pro/ko/llms.txt # Google 그만큼`@mastra/auth-google`패키지는 Google Workspace를 사용하여 Mastra에 대한 인증 및 역할 기반 액세스 제어를 제공합니다. 암호화된 세션 쿠키를 사용하여 OAuth 2.0/OIDC 로그인 흐름을 지원하고, Google ID 토큰을 확인하고, Google Workspace 그룹을 Mastra 권한에 매핑합니다. Studio 사용자가 Google로 로그인할 때 이 기능을 사용하세요. 액세스는 하나 이상의 Google Workspace 도메인으로 제한되어야 합니다. ## 전제조건 이 가이드에서는 Google Workspace 인증을 사용합니다. 다음을 확인하세요. 1. Google Cloud 프로젝트 만들기 또는 선택 2. 웹 애플리케이션용 OAuth 클라이언트 설정 3. 승인된 리디렉션 URI에 Mastra SSO 콜백 URL을 추가하세요. 4. RBAC를 사용하려는 경우 Google Workspace 그룹을 구성하세요. Google 그룹스 RBAC의 경우 도메인 전체 위임으로 Google Workspace 서비스 계정을 구성하고 여기에 Directory API 읽기 전용 그룹 범위를 부여합니다. ```text 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`세션 쿠키를 암호화합니다. 생략하면 서버를 다시 시작해도 유지되지 않는 자동 생성 값이 사용됩니다. 프로덕션을 위해 명시적으로 설정합니다. > > `MastraAuthGoogle`은 `GOOGLE_*` 인증 변수를 자동으로 읽습니다. 위에 표시된 서비스 계정 변수는 `MastraRBACGoogle`에 전달하는 구성 코드에서 읽습니다. ## 설치 `MastraAuthGoogle` 클래스를 사용하기 전에 `@mastra/auth-google` 패키지를 설치하세요. **npm**: ```bash npm install @mastra/auth-google ``` **pnpm**: ```bash pnpm add @mastra/auth-google ``` **Yarn**: ```bash yarn add @mastra/auth-google ``` **Bun**: ```bash bun add @mastra/auth-google ``` ## 사용 예 ### 환경 변수를 사용한 기본 사용법 위의 환경 변수를 설정하면 모든 생성자 매개변수는 선택사항입니다. ```typescript import { Mastra } from '@mastra/core' import { MastraAuthGoogle } from '@mastra/auth-google' export const mastra = new Mastra({ server: { auth: new MastraAuthGoogle(), }, }) ``` > **경고:** Workspace 액세스를 적용하려면 `allowedDomains` 또는 `GOOGLE_ALLOWED_DOMAINS`를 사용하세요. Mastra는 이메일 주소 접미사가 아니라 Google에서 검증한 `hd` 클레임을 검사합니다. ### 맞춤 구성 환경 변수에 의존하지 않으려면 생성자 옵션을 직접 전달하세요. ```typescript 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 그룹스 RBAC로 인증 Google Workspace 그룹을 Mastra 권한에 매핑하려면 `MastraRBACGoogle`을 추가하세요. ```typescript 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(Auth0, Clerk 등)를 사용하고 RBAC에는 Google Workspace 그룹을 사용하세요. 다른 Provider의 사용자 객체에서 Google Directory API 사용자 키를 확인하려면 `getUserKey` 함수를 전달하세요. ```typescript 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](https://mastra.zisheng.pro/ko/reference/auth/google)을 참조하세요. ## 역할 매핑 `roleMapping` 옵션은 Google Workspace 그룹 이메일 주소를 Mastra 권한 문자열 배열에 매핑합니다. 권한은 `resource:action` 패턴을 따르며 와일드카드를 지원합니다. ```typescript 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` 키는 다른 어떤 키와도 일치하지 않는 Google Workspace 그룹에 속한 사용자에게 권한을 할당합니다. ## 클라이언트 측 설정 인증이 활성화되면 Mastra 경로에 대한 요청에 인증이 필요합니다. `GOOGLE_CLIENT_SECRET`으로 SSO를 활성화하면 `MastraAuthGoogle`은 Google 로그인을 사용하고 로그인 후 암호화된 세션 쿠키를 설정합니다. ### 쿠키 세션(권장) 교차 출처 요청의 경우(예: `:3000`의 프런트엔드에서 `:4111`의 Mastra를 호출하는 경우) Mastra 서버에서 CORS 자격 증명을 활성화하세요. ```typescript export const mastra = new Mastra({ server: { auth: new MastraAuthGoogle(), cors: { origin: 'http://localhost:3000', credentials: true, }, }, }) ``` 자격 증명을 포함하도록 클라이언트를 구성합니다. ```typescript import { MastraClient } from '@mastra/client-js' export const mastraClient = new MastraClient({ baseUrl: 'http://localhost:4111', credentials: 'include', }) ``` ### 무기명 토큰 Google ID 토큰을 Bearer 토큰으로 전달할 수도 있습니다. Mastra는 Google의 JWKS(JSON 웹 키 세트) 엔드포인트에 대해 토큰을 확인합니다. ```typescript 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](https://mastra.zisheng.pro/ko/docs/server/mastra-client)를 참조하세요. ### 인증된 요청 만들기 **MastraClient**: ```typescript import { mastraClient } from '../lib/mastra-client' const agent = mastraClient.getAgent('weatherAgent') const response = await agent.generate('Weather in London') console.log(response) ``` **cURL**: ```bash curl -X POST http://localhost:4111/api/agents/weatherAgent/generate \ -H "Content-Type: application/json" \ -H "Authorization: Bearer " \ -d '{ "messages": "Weather in London" }' ``` ## 문제 해결 - **로그인 후 401 발생**: `GOOGLE_CLIENT_ID`, `GOOGLE_CLIENT_SECRET`, `GOOGLE_REDIRECT_URI`가 Google Cloud OAuth 클라이언트와 일치하는지 확인하세요. - **Workspace 사용자가 거부됨**: `GOOGLE_ALLOWED_DOMAINS`가 Google ID 토큰의 `hd` 클레임과 일치하는지 확인하세요. - **일반 Gmail 계정이 거부됨**: Gmail 계정에는 Workspace `hd` 클레임이 없으므로 `allowedDomains`가 구성된 경우 예상되는 동작입니다. - **RBAC가 기본 권한을 반환함**: 사용자에 대해 확인된 역할이 없습니다. 사용자 이메일 또는 사용자 지정 `getUserKey`, Google 그룹 멤버십, `roleMapping`을 확인하세요. Directory API 조회가 실패하면 Provider는 `_default`를 반환하는 대신 오류를 발생시킵니다. - **교차 출처로 쿠키가 전송되지 않음**: `MastraClient`에서 `credentials: "include"`를 설정하고, 프런트엔드 출처 및 `credentials: true`로 `server.cors`를 구성하세요. - **다시 시작하면 세션이 손실됨**: `GOOGLE_COOKIE_PASSWORD`를 32자 이상의 안정적인 값으로 설정하세요. 설정하지 않으면 개발 환경에서 자동 생성된 키가 사용되며 다시 시작할 때마다 변경됩니다. ## 관련된 - [인증 개요](https://mastra.zisheng.pro/ko/docs/server/auth) - [복합 인증](https://mastra.zisheng.pro/ko/docs/server/auth/composite-auth) - [MastraAuthGoogle 참조](https://mastra.zisheng.pro/ko/reference/auth/google)