From 2f0cd8c82bfd93fd3a7df1b5bf95cd5d688fc12d Mon Sep 17 00:00:00 2001 From: "iVampireSP.com" Date: Tue, 24 Oct 2023 16:20:07 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20jwt?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .env.example | 5 ++++- package.json | 1 + src/config/express.ts | 22 ++++++++++++++++++++++ 3 files changed, 27 insertions(+), 1 deletion(-) diff --git a/.env.example b/.env.example index bf36a73..0ee5859 100644 --- a/.env.example +++ b/.env.example @@ -4,4 +4,7 @@ DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=test DB_USERNAME=root -DB_PASSWORD= \ No newline at end of file +DB_PASSWORD= + +JWT_SECRET=test +JWT_ALGORITHM=HS256 \ No newline at end of file diff --git a/package.json b/package.json index e3078a1..3f2b152 100644 --- a/package.json +++ b/package.json @@ -5,6 +5,7 @@ "license": "MIT", "dependencies": { "express": "^4.18.2", + "express-jwt": "^8.4.1", "morgan": "^1.10.0", "mysql2": "^3.6.2", "path": "^0.12.7", diff --git a/src/config/express.ts b/src/config/express.ts index 1d9b2d1..2bb8183 100644 --- a/src/config/express.ts +++ b/src/config/express.ts @@ -1,5 +1,6 @@ import express from 'express'; import logger from 'morgan' +import {expressjwt} from "express-jwt"; const app = express(); @@ -7,5 +8,26 @@ app.use(logger('dev')); app.use(express.json()); app.use(express.urlencoded({ extended: false })); + +// JWT +app.use( + expressjwt({ + secret: Buffer.from(process.env.JWT_SECRET, "base64"), + algorithms: ["HS256"], + issuer: "testing", + }) +); + +app.use((err: express.ErrorRequestHandler, req: express.Request, res: express.Response, next: express.NextFunction) => { + if (err.name === "UnauthorizedError") { + res.status(401).send({ + "message": "Invalid token" + }); + } else { + next(err); + } +}); + + export default app;