더 나은 인증
그만큼@mastra/auth-better-auth패키지는 Better Auth를 사용하여 Mastra에 대한 인증을 제공합니다. Better Auth 인스턴스를 사용하여 들어오는 요청을 확인하고 다음을 통해 Mastra 서버와 통합됩니다.server.auth옵션.
전제조건전제조건에 대한 직접 링크
이 예에서는 Better Auth를 사용합니다. Better Auth 인스턴스가 구성되어 있고 환경 변수가 설정되어 있는지 확인하세요.
# 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 설치 가이드에 따라 /api/auth/* 경로(또는 구성한 기본 경로)를 마운트하세요.
설치설치에 대한 직접 링크
설치하다@mastra/auth-better-auth package:
- npm
- pnpm
- Yarn
- Bun
npm install @mastra/auth-better-auth
pnpm add @mastra/auth-better-auth
yarn add @mastra/auth-better-auth
bun add @mastra/auth-better-auth
사용예사용예에 대한 직접 링크
먼저 Better Auth 인스턴스를 만듭니다.
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와 함께 사용하십시오.
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를 참조하세요.
맞춤 인증맞춤 인증에 대한 직접 링크
const mastraAuth = new MastraAuthBetterAuth({
auth,
async authorizeUser(user) {
// Example: only allow verified emails
return user?.user?.emailVerified === true
},
})
경로 구성경로 구성에 대한 직접 링크
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 자격 증명을 활성화하세요.
export const mastra = new Mastra({
server: {
auth: mastraAuth,
cors: {
origin: 'http://localhost:3000', // your frontend origin
credentials: true,
},
},
})
그런 다음 자격 증명을 포함하도록 클라이언트를 구성합니다.
import { MastraClient } from '@mastra/client-js'
export const mastraClient = new MastraClient({
baseUrl: 'http://localhost:4111',
credentials: 'include',
})
API를 직접 호출하는 경우 fetch에도 자격 증명을 전달하세요.
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:
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를 참조하세요.
인증된 요청 만들기인증된 요청 만들기에 대한 직접 링크
- React
- cURL
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 <button onClick={handleClick}>Test Agent</button>
}
curl -X POST http://localhost:4111/api/agents/weatherAgent/generate \
-H "Content-Type: application/json" \
-H "Authorization: Bearer <your-token>" \
-d '{
"messages": "Weather in London"
}'
문제 해결문제 해결에 대한 직접 링크
- 모든 요청에 401 발생: Better Auth 핸들러가 마운트되어 있고 앱에서 유효한 세션을 생성할 수 있는지 확인하세요. 클라이언트가 세션 쿠키 또는
Authorization: Bearer <signed-token>헤더를 전송하는지 확인하세요. - 교차 출처로 쿠키가 전송되지 않음:
MastraClient에서credentials: "include"를 설정하고, 프런트엔드 출처 및credentials: true로server.cors를 구성하세요. - Bearer 토큰이 거부됨: 원시 토큰이나 서명되지 않은 토큰이 아니라 완전히 서명된 세션 토큰(
authClient.getSession())을 전달해야 합니다. - 기본 URL 문제:
betterAuth({ ... })에서baseURL을 설정하거나BETTER_AUTH_URL을 설정하세요. - DB 연결 오류:
DATABASE_URL과 데이터베이스 Provider 구성을 확인하세요.