Getting Started

Last updated


This page walks from installation to a first login, verification, and logout in a runnable Express app.

Prerequisites


ItemRequirement
Node.js20 or higher (package.json engines)
Express4.18 or higher (peer dependency)
RedisA reachable Redis server
Cookie parsingcookie-parser or equivalent; the package reads tokens from req.cookies
KeysAn EC P-256 key pair; the signing algorithm is fixed to ES256

Installation


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

Generate ES256 Keys


  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 or HMAC keys cannot sign with ES256, so CreateJWT() throws.

First App


  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 means a suspicious request; otherwise a plain guest
  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. // Issue tokens after verifying credentials
  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. // Key loading failed or Redis is unreachable
  56. console.error(err);
  57. process.exit(1);
  58. });

Verify It Works


  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

With isProd: false the cookie domain is fixed to localhost, so use http://localhost rather than 127.0.0.1; otherwise neither browsers nor curl send the cookie back.

Next Steps


中文