添加 jwt
This commit is contained in:
parent
dd97d2bf95
commit
2f0cd8c82b
@ -4,4 +4,7 @@ DB_HOST=127.0.0.1
|
||||
DB_PORT=3306
|
||||
DB_DATABASE=test
|
||||
DB_USERNAME=root
|
||||
DB_PASSWORD=
|
||||
DB_PASSWORD=
|
||||
|
||||
JWT_SECRET=test
|
||||
JWT_ALGORITHM=HS256
|
@ -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",
|
||||
|
@ -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;
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user