nestjs10.x使用jwt生成token

1 安装依赖:

pnpm install --save @nestjs/jwt
 
pnpm install passport passport-jwt @nestjs/jwt
 
pnpm 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);
      
        // 生成token
        let 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 '更新成功';
    }

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值