가이드

BFF 서버 인증

새 서버 연동에는 Authorization Code + PKCE 방식을 권장합니다. 브라우저에는 60초짜리 일회용 코드만 전달되고 Authon 토큰은 서버 간 교환에서만 반환됩니다.

권장 흐름

PKCE verifier와 state는 HttpOnly 트랜잭션 쿠키 또는 서버 저장소에 보관하세요. 콜백에서는 state를 검증하고 secret key로 코드를 교환한 다음 서비스 자체 HttpOnly 세션을 만듭니다.

1. 서버가 state와 PKCE 쌍을 생성
2. 브라우저가 코드 모드로 Authon 로그인
3. Authon이 등록된 콜백으로 일회용 코드 전달
4. 서버가 secret key로 코드 교환 POST /v1/auth/token/exchange
5. 서버가 자체 HttpOnly 세션 생성
app/auth/start/route.ts
import { createAuthonAuthorizationRequest } from '@authon/nextjs/server';

export async function POST() {
  const { authorization } = await createAuthonAuthorizationRequest({
    redirectUri: 'https:0
  });
  return Response.json(authorization, {
    headers: { 'Cache-Control': 'no-store' },
  });
}
sign-in.ts
import { Authon } from '@authon/js';

const authorization = await fetch('/auth/start', { method: 'POST' })
  .then((response) => response.json());
const authon = new Authon('pk_live_...', { sessionMode: 'bff' });
await authon.openSignIn(authorization);
app/api/auth/authon/callback/route.ts
import { handleAuthonAuthorizationCallback } from '@authon/nextjs/server';

export async function GET(request: Request) {
  const url = new URL(request.url);
  const result = await handleAuthonAuthorizationCallback({
    code: url.searchParams.get('code')!,
    state: url.searchParams.get('state')!,
    redirectUri: 'https:0
    secretKey: process.env.AUTHON_SECRET_KEY!,
  });

  await createApplicationSession(result.user, result);
  return Response.redirect(new URL('/app', url));
}
AUTHON_SECRET_KEY와 AUTHON_TRANSACTION_SECRET은 서버 환경변수로만 설정하세요. 콜백 URL은 대시보드에서 전체 URL이 정확히 일치하도록 등록해야 합니다.

레거시 SPA 토큰 모드

기존 SPA를 위해 token 모드는 계속 지원하지만 새 BFF 연동에는 위 코드 모드를 사용하세요. token 모드는 브라우저 JavaScript가 Authon 토큰을 다룹니다.

frontend.ts
import { Authon } from '@authon/js';

const authon = new Authon('pk_live_...');

authon.on('signedIn', async (user) => {
  const authonToken = authon.getToken();

  // Send token to your backend
  const res = await fetch('/api/auth/authon', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ token: authonToken }),
  });

  const { serviceToken } = await res.json();
  // Use serviceToken for your API calls
});

await authon.openSignIn();

2. 백엔드: 토큰 검증 + 세션 발급

서비스 백엔드에서 Authon의 토큰 검증 API를 호출하여 토큰이 유효한지 확인합니다. 유효하면 유저를 생성(또는 조회)하고 서비스 자체 JWT를 발급합니다.

routes/auth.ts
app.post('/api/auth/authon', async (req, res) => {
  const { token } = req.body;
  if (!token) return res.status(400).json({ error: 'Token required' });

  // 1. Verify the Authon token
  const verify = await fetch('https:1
    headers: { Authorization: 4 },
  });
  const { valid, user: authonUser } = await verify.json();

  if (!valid || !authonUser) {
    return res.status(401).json({ error: 'Invalid Authon token' });
  }

  2
  let user = await db.users.findByEmail(authonUser.email);
  if (!user) {
    user = await db.users.create({
      email: authonUser.email,
      name: authonUser.displayName,
      provider: 'authon',
    });
  }

  3
  const serviceToken = jwt.sign(
    { userId: user.id, email: user.email },
    process.env.JWT_SECRET,
    { expiresIn: '7d' }
  );

  res.json({ serviceToken, user });
});

토큰 검증 API

GET/v1/auth/token/verify

Authon JWT를 검증하고 유저 정보를 반환합니다. API 키 없이 호출 가능합니다.

요청

bash
curl https://api.authon.dev/v1/auth/token/verify \
  -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIs..."

응답

json
{
  "valid": true,
  "payload": {
    "sub": "user-uuid",
    "projectId": "project-uuid",
    "type": "access",
    "iat": 1711584000,
    "exp": 1711584900
  },
  "user": {
    "id": "user-uuid",
    "email": "user@example.com",
    "displayName": "Alan Kim",
    "avatarUrl": null,
    "emailVerified": true
  }
}
!

토큰 검증은 반드시 서버사이드에서 수행하세요. 프론트엔드에서 토큰을 자체 검증하면 보안상 위험합니다. 이메일만으로 서비스 JWT를 발급하는 것도 위험합니다 — 반드시 Authon 토큰을 검증한 후에 발급하세요.

getToken() 상세

authon.getToken()은 Authon이 발급한 JWT(JSON Web Token)를 반환합니다. 이 토큰은 HS256으로 서명되며, 15분 후 만료됩니다. 만료 시 SDK가 자동으로 리프레시합니다.

항목값
형식JWT (HS256)
만료15 분
자동 갱신예 (SDK가 자동 처리)
Payload.sub유저 UUID
Payload.projectId프로젝트 UUID

연동 체크리스트

Authon — 범용 인증 플랫폼