1 安装依赖:
pnpm install --save @nestjs/jwtpnpm install passport passport-jwt @nestjs/jwtpnpm install @types/passport-jwt --save-dev
2 可以使用命令新建auth鉴权文件夹
nest g mo auth // auth.module.ts
nest g s auth // auth.service.ts
nest g co auth //auth.controller.ts
3 在auth.module.ts配置jwt
import { Module } from '@nestjs/common';
import { AuthController } from './auth.controller';
import { AuthService } from './auth.service';
import { UserModule } from '../user/user.module';
import { PassportModule } from '@nestjs/passport';
import { JwtModule } from '@nestjs/jwt';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { JwtStrategy } from './auth.strategy';@Module({imports: [PassportModule,JwtModule.registerAsync({imports: [ConfigModule],useFactory: async (configService: ConfigService) => {return {secret: configService.get('jwt').secret,//jwt密钥signOptions: { expiresIn: '60s' }}},inject: [ConfigService]}),],exports: [JwtModule],controllers: [AuthController],providers: [AuthService,JwtStrategy],
})
export class AuthModule {}
4 其中密钥我通过外部文件引入,也可以使用.env引入
configService.get('jwt').secret,
5. 然后在auth.service.ts中, 生成token,返回给前端
import { HttpException, Injectable } from '@nestjs/common';
import { UserService } from '../user/user.service';
import { JwtService } from '@nestjs/jwt';@Injectable()
export class AuthService {constructor(private userService: UserService,private jwt: JwtService,) {}//登录async manageLogin(username: string, password: string) {const user: ManageUserEntity = await this.userService.findUserName(username);// 生成tokenlet token = await this.jwt.signAsync({username: user.username,id: user.id})return token}}
6. 验证token, 要在auth中新建auth.strategy.ts
import { Injectable, UnauthorizedException } from "@nestjs/common";
import { PassportStrategy } from "@nestjs/passport";
import { Strategy, ExtractJwt } from "passport-jwt";
import { ConfigService } from '@nestjs/config';/*** JWT策略* */@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {//对前端传递来的token进行解析constructor(private configService: ConfigService,) {super({jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),//校验逻辑token 已封装ignoreExpiration: false,secretOrKey: configService.get('jwt').secret,});}/*** 验证token* @param payload*/async validate(payload: any) {return {id: payload.id, username: payload.username}}
}
其中在validate中,会返回已经解析好的用户id和名称。
7. 然后通过路由验证下token
import {UseGuards, Req } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';@Post('/update')@UseGuards(AuthGuard('jwt'))async saveManage(@Body() dto: CreateManageDto, @Req() req) {console.log(req.user)return '更新成功';}