nest.js实现jwt的签发与验证

安装相关依赖包

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:

import {Controller,Get, UseGuards} 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():any {
        return this.PassportService.findAll()
    }

}

  • 7
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值