安装相关依赖包
npm i @nestjs/passport passport passport-local
npm i -D @types/passport-local
在src中新建auth文件夹,并在文件夹中新建jwt.strategy.ts文件,代码如下:
import { ExtractJwt, Strategy } from "passport-jwt";
import { PassportStrategy } from '@nestjs/passport'
import { Injectable } from '@nestjs/common'
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {
constructor() {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: 'P@ssp0rt20HJ21@@$$' //私钥
})
}
async validate(payload:any) {
return payload
}
}
src/app.module.ts中添加以下代码
import { JwtStrategy } from './auth/jwt.strategy'
//找到providers: [AppService]换成
providers: [AppService, JwtStrategy]
签发部分:
Service:
import { JwtService } from "@nestjs/jwt/dist"
export class PassportService {
constructor(
private readonly jwtService: JwtService
) { }
login() {
// ... 登录逻辑
const loginInfo = {}
// 签发token
loginInfo.token = this.jwtService.sign({loginInfo})
return loginInfo
}
}
Module:
import { Module } from "@nestjs/common";
import { PassportController } from "./passport.controller";
import { PassportService } from "./passport.service";
import { JwtModule } from "@nestjs/jwt/dist/jwt.module";
@Module({
imports: [
JwtModule.register({
secret: 'P@ssp0rt20HJ21@@$$', // 私钥
signOptions: { expiresIn: '6h'} //过期时间
})
],
controllers: [PassportController],
providers: [PassportService]
})
在需要验证jwt的controller并提取jwt中保存的信息:
import {Controller,Get, UseGuards, Req} from '@nestjs/common'
import { AuthGuard } from '@nestjs/passport'
@Controller('passport')
@UseGuards(AuthGuard('jwt')) // 当前controller所有接口都验证
export class PassportController {
constructor(private readonly PassportService: PassportService) {}
@UseGuards(AuthGuard('jwt')) // 单个接口验证
@Get()
findAll(@Req() req):any {
console.log(req.user) // 提取jwt中保存的数据
return this.PassportService.findAll()
}
}