改进 JWT

This commit is contained in:
iVampireSP.com 2023-10-24 16:42:02 +08:00
parent 2f0cd8c82b
commit ad4811f8a1
No known key found for this signature in database
GPG Key ID: 2F7B001CA27A8132
5 changed files with 57 additions and 9 deletions

View File

@ -7,4 +7,5 @@ DB_USERNAME=root
DB_PASSWORD=
JWT_SECRET=test
JWT_ALGORITHM=HS256
#JWT_ALGORITHM=HS256
JWT_ISSUER=testing

View File

@ -1,6 +1,7 @@
import express from 'express';
import logger from 'morgan'
import {expressjwt} from "express-jwt";
import {getUser} from "./middleware";
const app = express();
@ -10,13 +11,15 @@ app.use(express.urlencoded({ extended: false }));
// JWT
app.use(
expressjwt({
secret: Buffer.from(process.env.JWT_SECRET, "base64"),
algorithms: ["HS256"],
issuer: "testing",
})
);
// app.use(
// expressjwt({
// secret: Buffer.from(process.env.JWT_SECRET, "base64"),
// algorithms: ["HS256"],
// issuer: process.env.JWT_ISSUER,
// })
// );
app.use(getUser)
app.use((err: express.ErrorRequestHandler, req: express.Request, res: express.Response, next: express.NextFunction) => {
if (err.name === "UnauthorizedError") {

30
src/config/middleware.ts Normal file
View File

@ -0,0 +1,30 @@
import {NextFunction, Request, Response} from 'express'
import {JWTRequest} from "../types/JWTRequest";
const getUser = (req: JWTRequest, res: Response, next: NextFunction) => {
// 从 header 中获取 token
const token = req.headers.authorization.split(' ')[1]
// 获取 JWT 的用户部分
const base64Url = token.split('.')[1]
const base64 = base64Url.replace('-', '+').replace('_', '/')
req.auth = Object.assign({}, req.auth, JSON.parse(Buffer.from(base64, 'base64').toString()))
next()
}
// function hasRole(role: string) {
// return (req: JWTRequest, res: Response, next: NextFunction) => {
// if (req.user.role === role) {
// next()
// } else {
// res.status(403).send('Unauthorized')
// }
// }
// }
export {
// hasRole,
getUser
}

View File

@ -1,10 +1,18 @@
import {Request, Response} from "express";
import {User} from "../entity/User";
import manager from "../config/manager";
import {JWTRequest} from "../types/JWTRequest";
class UserController {
public async index(request: Request, response: Response) {
public async index(request: JWTRequest, response: Response) {
const authorization = request.auth.user.id
console.log(authorization)
return response.json({
message: 'Hello World! From user'
})
const user = new User()
user.name = "Timber"

6
src/types/JWTRequest.ts Normal file
View File

@ -0,0 +1,6 @@
import * as jwt from "jsonwebtoken";
import * as express from "express";
export type JWTRequest<T = jwt.JwtPayload> = express.Request & {
auth?: T;
};