> Discover all available pages from the documentation index: https://mastra.zisheng.pro/ko/llms.txt # 더 나은 인증 그만큼`@mastra/auth-better-auth`패키지는 Better Auth를 사용하여 Mastra에 대한 인증을 제공합니다. Better Auth 인스턴스를 사용하여 들어오는 요청을 확인하고 다음을 통해 Mastra 서버와 통합됩니다.`server.auth`옵션. ## 전제조건 이 예에서는 Better Auth를 사용합니다. Better Auth 인스턴스가 구성되어 있고 환경 변수가 설정되어 있는지 확인하세요. ```env # Required by Better Auth BETTER_AUTH_SECRET=... # at least 32 chars BETTER_AUTH_URL=http://localhost:3000 # Example DB URL used by the snippet below (adjust for your setup) DATABASE_URL=postgres://... ``` > **노트:** Better Auth에서는 보안과 안정성을 위해 `baseURL`을 명시적으로 설정하거나 `BETTER_AUTH_URL`을 통해 설정하는 것이 좋습니다. 앱에서 사용자가 로그인하거나 세션을 만들 수 있도록 Better Auth 핸들러를 아직 마운트하지 않았다면 [Better Auth 설치 가이드](https://www.better-auth.com/docs/installation)에 따라 `/api/auth/*` 경로(또는 구성한 기본 경로)를 마운트하세요. ## 설치 설치하다`@mastra/auth-better-auth` package: **npm**: ```bash npm install @mastra/auth-better-auth ``` **pnpm**: ```bash pnpm add @mastra/auth-better-auth ``` **Yarn**: ```bash yarn add @mastra/auth-better-auth ``` **Bun**: ```bash bun add @mastra/auth-better-auth ``` ## 사용예 먼저 Better Auth 인스턴스를 만듭니다. ```ts import { betterAuth } from 'better-auth' export const auth = betterAuth({ database: { provider: 'postgresql', url: process.env.DATABASE_URL!, }, emailAndPassword: { enabled: true, }, baseURL: process.env.BETTER_AUTH_URL, secret: process.env.BETTER_AUTH_SECRET, }) ``` 그런 다음 Mastra와 함께 사용하십시오. ```ts import { Mastra } from '@mastra/core' import { MastraAuthBetterAuth } from '@mastra/auth-better-auth' import { auth } from '@/lib/auth' const mastraAuth = new MastraAuthBetterAuth({ auth, }) export const mastra = new Mastra({ server: { auth: mastraAuth, }, }) ``` 사용 가능한 모든 구성 옵션은 [MastraAuthBetterAuth](https://mastra.zisheng.pro/ko/reference/auth/better-auth)를 참조하세요. ## 맞춤 인증 ```ts const mastraAuth = new MastraAuthBetterAuth({ auth, async authorizeUser(user) { // Example: only allow verified emails return user?.user?.emailVerified === true }, }) ``` ## 경로 구성 ```ts const mastraAuth = new MastraAuthBetterAuth({ auth, public: ['/health', '/api/status'], protected: ['/api/*', '/admin/*'], }) ``` ### 일치 규칙 - `public`과 `protected`는 정확한 경로, 와일드카드 패턴(예: `/api/*`), 경로 매개변수(예: `/users/:id`)를 받습니다. - 메서드별 규칙에는 `["/api/agents", ["GET", "POST"]]` 같은 튜플을 사용하세요. - 경로가 `public`과 `protected`에 모두 일치하면 `public`이 우선하며 인증이 필요하지 않습니다. - 둘 다 일치하지 않으면 경로에 `requiresAuth: false`가 명시적으로 지정되지 않은 한 기본적으로 보호된 것으로 간주합니다. ## 클라이언트 측 설정 인증이 활성화되면 Mastra의 내장 경로에 대한 요청에 인증이 필요합니다. 실제로 이는 클라이언트가 Better Auth 설정에서 인증된 요청에 사용하는 모든 자격 증명을 보내야 함을 의미합니다. ### 쿠키 세션(권장) Better Auth 설정에서 쿠키를 사용하는 경우 자격 증명을 보내도록 클라이언트를 구성하세요. 교차 출처 요청(예: Next.js `:3000`에서 `:4111`의 Mastra 호출)의 경우 Mastra 서버에서 CORS 자격 증명을 활성화하세요. ```ts export const mastra = new Mastra({ server: { auth: mastraAuth, cors: { origin: 'http://localhost:3000', // your frontend origin credentials: true, }, }, }) ``` 그런 다음 자격 증명을 포함하도록 클라이언트를 구성합니다. ```ts import { MastraClient } from '@mastra/client-js' export const mastraClient = new MastraClient({ baseUrl: 'http://localhost:4111', credentials: 'include', }) ``` API를 직접 호출하는 경우 `fetch`에도 자격 증명을 전달하세요. ```ts await fetch('http://localhost:4111/api/agents/weatherAgent/generate', { method: 'POST', headers: { 'Content-Type': 'application/json', }, credentials: 'include', body: JSON.stringify({ messages: 'Weather in London' }), }) ``` ### 무기명 토큰 서명된 세션 토큰을 Bearer 토큰으로 전달할 수 있습니다. Better Auth 클라이언트 세션에서 이를 검색하여`Authorization` header: ```ts import { MastraClient } from '@mastra/client-js' import { authClient } from './auth-client' // your Better Auth client const session = await authClient.getSession() export const mastraClient = new MastraClient({ baseUrl: 'http://localhost:4111', headers: { Authorization: `Bearer ${session.data?.session.token}`, }, }) ``` 더 많은 구성 옵션은 [Mastra Client SDK](https://mastra.zisheng.pro/ko/docs/server/mastra-client)를 참조하세요. ### 인증된 요청 만들기 **React**: ```tsx import { mastraClient } from '../lib/mastra-client' export const TestAgent = () => { async function handleClick() { const agent = mastraClient.getAgent('weatherAgent') const response = await agent.generate('Weather in London') console.log(response) } return } ``` **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 발생**: Better Auth 핸들러가 마운트되어 있고 앱에서 유효한 세션을 생성할 수 있는지 확인하세요. 클라이언트가 세션 쿠키 또는 `Authorization: Bearer ` 헤더를 전송하는지 확인하세요. - **교차 출처로 쿠키가 전송되지 않음**: `MastraClient`에서 `credentials: "include"`를 설정하고, 프런트엔드 출처 및 `credentials: true`로 `server.cors`를 구성하세요. - **Bearer 토큰이 거부됨**: 원시 토큰이나 서명되지 않은 토큰이 아니라 완전히 서명된 세션 토큰(`authClient.getSession()`)을 전달해야 합니다. - **기본 URL 문제**: `betterAuth({ ... })`에서 `baseURL`을 설정하거나 `BETTER_AUTH_URL`을 설정하세요. - **DB 연결 오류**: `DATABASE_URL`과 데이터베이스 Provider 구성을 확인하세요.