From ebc405f548558fea4cf8b9ad8bec0a793b447185 Mon Sep 17 00:00:00 2001 From: Jeremy Yin Date: Tue, 9 Jul 2019 21:39:12 +0800 Subject: [PATCH] =?UTF-8?q?=E8=AF=B7=E6=B1=82token=E9=AA=8C=E8=AF=81?= =?UTF-8?q?=E7=AD=96=E7=95=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/modules/auth/strategies/jwt.strategy.ts | 27 +++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 src/modules/auth/strategies/jwt.strategy.ts diff --git a/src/modules/auth/strategies/jwt.strategy.ts b/src/modules/auth/strategies/jwt.strategy.ts new file mode 100644 index 0000000..a4a05c0 --- /dev/null +++ b/src/modules/auth/strategies/jwt.strategy.ts @@ -0,0 +1,27 @@ +import { Injectable, UnauthorizedException } from "@nestjs/common"; +import { PassportStrategy } from "@nestjs/passport"; +import { Strategy, ExtractJwt } from "passport-jwt"; +import { JwtPayload } from "../auth.interface"; +import { UserService } from "../../user/user.service"; + +@Injectable() +export class JwtStrategy extends PassportStrategy(Strategy) { + constructor( + private readonly userService: UserService + ) { + super({ + jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), + secretOrKey: 'nDSAR3+K4pLD+HIl9xWFY/n7maMxLwPTj5gscZvd9Vo=', + }) + } + + async validate(payload: JwtPayload) { + console.log(payload) + const { username } = payload + const entity = await this.userService.findByUserName(username) + if (!entity) { + throw new UnauthorizedException('用户不存在') + } + return entity + } +} \ No newline at end of file