快速開始

最後更新


本頁從安裝到完成第一次登入、驗證與登出,串起一個可執行的 Express 應用。

前置需求


項目需求
Node.js20 以上(package.json engines)
Express4.18 以上(peer dependency)
Redis可連線的 Redis 伺服器
Cookie 解析cookie-parser 或同等中介軟體;套件從 req.cookies 讀取 Token
金鑰EC P-256 金鑰對;簽章演算法固定為 ES256

安裝


  1. npm install @pardnchiu/jwt-auth express cookie-parser

產生 ES256 金鑰


  1. mkdir -p keys
  2. openssl ecparam -name prime256v1 -genkey -noout -out keys/private.pem
  3. openssl ec -in keys/private.pem -pubout -out keys/public.pem

RSA 或 HMAC 金鑰無法以 ES256 簽章,CreateJWT() 會拋出錯誤。

第一個應用


  1. import express, { Request, Response, NextFunction } from "express";
  2. import cookieParser from "cookie-parser";
  3. import { JWTAuth } from "@pardnchiu/jwt-auth";
  4. const app = express();
  5. app.use(express.json());
  6. app.use(cookieParser());
  7. async function requireAuth(req: Request, res: Response, next: NextFunction) {
  8. try {
  9. const result = await JWTAuth.VerifyJWT(req, res);
  10. if (!result.isAuth) {
  11. // isError 為 true 代表可疑請求,否則為一般訪客
  12. return res.status(result.isError ? 400 : 401).json({ error: "unauthorized" });
  13. }
  14. res.locals.user = result.data;
  15. next();
  16. } catch (err) {
  17. res.status(500).json({ error: (err as Error).message });
  18. }
  19. }
  20. app.post("/login", async (req, res) => {
  21. try {
  22. // 帳密驗證完成後簽發 Token
  23. const result = await JWTAuth.CreateJWT(req, res, {
  24. id: "user123",
  25. name: "John",
  26. email: "john@example.com",
  27. });
  28. res.json(result);
  29. } catch (err) {
  30. res.status(500).json({ error: (err as Error).message });
  31. }
  32. });
  33. app.get("/me", requireAuth, (req, res) => {
  34. res.json({ user: res.locals.user });
  35. });
  36. app.post("/logout", async (req, res) => {
  37. await JWTAuth.RevokeJWT(req, res);
  38. res.json({ ok: true });
  39. });
  40. async function main() {
  41. await JWTAuth.init({
  42. privateKeyPath: "./keys/private.pem",
  43. publicKeyPath: "./keys/public.pem",
  44. accessTokenExpires: 900,
  45. refreshTokenExpires: 604800,
  46. isProd: false,
  47. AccessTokenCookieKey: "access_token",
  48. RefreshTokenCookieKey: "refresh_id",
  49. redis: { host: "localhost", port: 6379 },
  50. checkUserExists: async (userId) => true,
  51. });
  52. app.listen(3000);
  53. }
  54. main().catch((err) => {
  55. // 金鑰讀取失敗或 Redis 無法連線
  56. console.error(err);
  57. process.exit(1);
  58. });

驗證是否運作


  1. curl -i -c jar.txt -X POST http://localhost:3000/login
  2. curl -i -b jar.txt http://localhost:3000/me
  3. curl -i -b jar.txt -X POST http://localhost:3000/logout
  4. curl -i -b jar.txt http://localhost:3000/me

isProd: false 時 cookie 的 domain 固定為 localhost,請以 http://localhost 而非 127.0.0.1 存取,否則瀏覽器與 curl 都不會回送 cookie。

下一步


EN