設定
最後更新
本頁列出
JWTAuth.init() 接收的 Config 每個欄位、預設值與驗證規則。欄位
| 欄位 | 型別 | 必要 | 預設值 | 說明 |
|---|---|---|---|---|
privateKeyPath | string | 二擇一 | — | 私鑰檔案路徑;有設定時覆蓋 privateKey |
privateKey | string | 二擇一 | — | 私鑰 PEM 內容 |
publicKeyPath | string | 二擇一 | — | 公鑰檔案路徑;有設定時覆蓋 publicKey |
publicKey | string | 二擇一 | — | 公鑰 PEM 內容 |
accessTokenExpires | number | 是 | — | Access Token 壽命(秒);同時是撤銷黑名單 TTL |
refreshTokenExpires | number | 是 | — | Refresh ID 壽命(秒),每次續期重設 |
isProd | boolean | 是 | — | 決定 cookie 的 secure、sameSite、domain |
domain | string | 否 | — | isProd 為 true 時的 cookie 網域;未設定時 cookie 不帶 domain 屬性(僅限當前主機) |
redis.host | string | 是 | localhost | Redis 主機 |
redis.port | number | 是 | 6379 | Redis 連接埠 |
redis.password | string | 否 | — | Redis 密碼 |
redis.db | number | 否 | 0 | Redis 資料庫編號 |
checkUserExists | (userId: string) => Promise<boolean> | 是 | — | 續期時確認使用者仍存在 |
AccessTokenCookieKey | string | 型別上必填 | access_token | Access Token cookie 名稱 |
RefreshTokenCookieKey | string | 型別上必填 | refresh_id | Refresh ID cookie 名稱 |
init 的驗證與錯誤
| 情況 | 結果 |
|---|---|
publicKey 與 publicKeyPath 都未提供 | 拋出 publicKey is required |
privateKey 與 privateKeyPath 都未提供 | 拋出 privateKey is required |
| 金鑰路徑不存在 | readFileSync 拋出的錯誤原樣傳出 |
| Redis 連線失敗 | 以 console.error 記錄後拋出 |
init() 會直接修改傳入的設定物件:讀入的金鑰寫回 publicKey/privateKey,cookie 名稱補上預設值。金鑰來源
- import { JWTAuth } from "@pardnchiu/jwt-auth";
- // 從環境變數讀取 PEM 內容,適合容器部署
- await JWTAuth.init({
- privateKey: process.env.JWT_PRIVATE_KEY,
- publicKey: process.env.JWT_PUBLIC_KEY,
- accessTokenExpires: 900,
- refreshTokenExpires: 604800,
- isProd: true,
- domain: "example.com",
- AccessTokenCookieKey: "access_token",
- RefreshTokenCookieKey: "refresh_id",
- redis: { host: "redis", port: 6379, password: process.env.REDIS_PASSWORD },
- checkUserExists: async (userId) => true,
- });
套件本身不讀取任何環境變數。
行程訊號
匯入套件時即註冊
SIGINT 與 SIGTERM 處理器:呼叫 JWTAuth.close() 後執行 process.exit(0)。應用若有自己的優雅關閉流程,需注意此處理器會在 Redis 斷線後立即結束行程。相關:Token 傳遞、API 參考