Bearer Token 인증
Bearer 플러그인은 브라우저 쿠키의 대안으로 Bearer 토큰을 사용한 인증을 가능하게 합니다. 요청을 가로채서 API로 전달하기 전에 Authorization 헤더에 Bearer 토큰을 추가합니다.
이것은 신중하게 사용해야 합니다. 쿠키를 지원하지 않거나 인증에 Bearer 토큰이 필요한 API에만 사용하도록 의도되었습니다. 부적절한 구현은 쉽게 보안 취약점으로 이어질 수 있습니다.
Bearer 플러그인 설치
인증 설정에 Bearer 플러그인을 추가합니다:
import { betterAuth } from "better-auth";
import { bearer } from "better-auth/plugins";
export const auth = betterAuth({
plugins: [bearer()]
});Bearer 토큰 사용 방법
1. Bearer 토큰 가져오기
성공적인 로그인 후, 응답 헤더에서 세션 토큰을 받게 됩니다. 이 토큰을 안전하게 저장합니다(예: localStorage):
const { data } = await authClient.signIn.email({
email: "user@example.com",
password: "securepassword"
}, {
onSuccess: (ctx)=>{
const authToken = ctx.response.headers.get("set-auth-token") // 응답 헤더에서 토큰 가져오기
// 토큰을 안전하게 저장 (예: localStorage)
localStorage.setItem("bearer_token", authToken);
}
});auth 클라이언트에서 전역적으로 설정할 수도 있습니다:
export const authClient = createAuthClient({
fetchOptions: {
onSuccess: (ctx) => {
const authToken = ctx.response.headers.get("set-auth-token") // 응답 헤더에서 토큰 가져오기
// 토큰을 안전하게 저장 (예: localStorage)
if(authToken){
localStorage.setItem("bearer_token", authToken);
}
}
}
});응답 상태 코드 또는 기타 조건에 따라 토큰을 지울 수 있습니다:
2. Auth 클라이언트 구성
모든 요청에 Bearer 토큰을 포함하도록 auth 클라이언트를 설정합니다:
export const authClient = createAuthClient({
fetchOptions: {
auth: {
type:"Bearer",
token: () => localStorage.getItem("bearer_token") || "" // localStorage에서 토큰 가져오기
}
}
});3. 인증된 요청 만들기
이제 인증된 API 호출을 할 수 있습니다:
// 이 요청은 자동으로 인증됩니다
const { data } = await authClient.listSessions();4. 요청별 토큰 (선택 사항)
개별 요청에 대해 토큰을 제공할 수도 있습니다:
const { data } = await authClient.listSessions({
fetchOptions: {
headers: {
Authorization: `Bearer ${token}`
}
}
});5. Auth 클라이언트 외부에서 Bearer 토큰 사용
Bearer 토큰은 auth 클라이언트를 사용하지 않는 경우에도 API에 대한 모든 요청을 인증하는 데 사용할 수 있습니다:
const token = localStorage.getItem("bearer_token");
const response = await fetch("https://api.example.com/data", {
headers: {
Authorization: `Bearer ${token}`
}
});
const data = await response.json();서버에서는 auth.api.getSession 함수를 사용하여 요청을 인증할 수 있습니다:
import { auth } from "@/auth";
export async function handler(req, res) {
const session = await auth.api.getSession({
headers: req.headers
});
if (!session) {
return res.status(401).json({ error: "Unauthorized" });
}
// 인증된 요청 처리
// ...
}옵션
requireSignature (boolean): 토큰이 서명되어야 합니다. 기본값: false.