逐步指南:在 Express.js 中创建 PASETO(平台无关安全令牌)

发布: (2025年12月28日 GMT+8 02:05)
2 min read
原文: Dev.to

Source: Dev.to

Cover image for Step‑by‑step Guide: Creating a PASETO (Platform‑Agnostic Security Token) in Express.js

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();

/**
 * Generate an Ed25519 key pair with tweetnacl
 */
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());

// issue token
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 });
  }
});

// verify token
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"}'

Token generation response

验证令牌

PASTE_YOUR_TOKEN_HERE 替换为你上面收到的令牌。

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

Token verification response

提示: 在生产环境中,你应该安全地存储密钥对,而不是在每次启动时重新生成。此演示设置旨在帮助你了解 PASETO 的工作原理。

Back to Blog

相关文章

阅读更多 »