단계별 가이드: Express.js에서 PASETO(Platform-Agnostic Security Token) 만들기

발행: (2025년 12월 28일 오전 03:05 GMT+9)
3 분 소요
원문: Dev.to

Source: Dev.to

Express.js에서 PASETO(플랫폼‑독립 보안 토큰)를 만드는 단계별 가이드 표지 이미지

1. 의존성 설치

한 번만 실행하세요:

npm install express paseto tweetnacl dotenv

2. .env 파일 만들기

PORT=3000

3. PASETO가 포함된 Express 서버 만들기

server.js 라는 파일을 생성합니다:

import express from "express";
import { V2 } from "paseto";
import nacl from "tweetnacl";
import dotenv from "dotenv";

dotenv.config();

/**
 * tweetnacl을 사용해 Ed25519 키 쌍 생성
 */
console.log("🟡 Generating Ed25519 key pair (v2.public) ...");
const keyPair = nacl.sign.keyPair(); // Uint8Arrays
const privateKey = Buffer.from(keyPair.secretKey);
const publicKey = Buffer.from(keyPair.publicKey);
console.log("✅ Keys ready, starting Express...");

const app = express();
app.use(express.json());

// 토큰 발급
app.post("/token", async (req, res) => {
  try {
    const payload = {
      userId: req.body.userId,
      role: req.body.role,
      issuedAt: new Date().toISOString(),
    };

    const token = await V2.sign(payload, privateKey, {
      issuer: "my-app",
      audience: "users",
      expiresIn: "1h",
    });

    res.json({ token });
  } catch (err) {
    console.error("❌ Token generation failed:", err);
    res.status(500).json({ error: err.message });
  }
});

// 토큰 검증
app.post("/verify", async (req, res) => {
  try {
    const { token } = req.body;
    const payload = await V2.verify(token, publicKey, {
      issuer: "my-app",
      audience: "users",
    });
    res.json({ valid: true, payload });
  } catch (err) {
    console.error("❌ Verification failed:", err);
    res.status(401).json({ error: "Invalid or expired token" });
  }
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`🚀 Server running on http://localhost:${PORT}`));

4. 서버 실행

node server.js

다음과 비슷한 출력이 표시됩니다:

🟡 Generating Ed25519 key pair (v2.public) ...
✅ Keys ready, starting Express...
🚀 Server running on http://localhost:3000

5. API 테스트

토큰 생성

curl -X POST http://localhost:3000/token \
  -H "Content-Type: application/json" \
  -d '{"userId":123,"role":"admin"}'

토큰 생성 응답

토큰 검증

아래 PASTE_YOUR_TOKEN_HERE 를 위에서 받은 토큰으로 교체하세요.

curl -X POST http://localhost:3000/verify \
  -H "Content-Type: application/json" \
  -d '{"token":"PASTE_YOUR_TOKEN_HERE"}'

토큰 검증 응답

팁: 실제 운영 환경에서는 매 시작 시마다 키를 생성하지 말고, 키 쌍을 안전하게 저장해 두어야 합니다. 이 데모 설정은 PASETO 작동 방식을 배우기 위한 목적입니다.

Back to Blog

관련 글

더 보기 »