nestjs学习笔记,登录验证

nestjs学习笔记

1、使用 @nestjs/jwt做登录验证
  • //安装 @nestjs/jwt
    yarn add @nestjs/jwt
    创建local.strategy.ts文件
import { PassportStrategy } from '@nestjs/passport';
import { IStrategyOptions, Strategy } from 'passport-local';
import { user } from '../entity/user.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { UserService } from '../user.service'
import { BadRequestException, Injectable } from '@nestjs/common';


@Injectable()
export class LocalStorage extends PassportStrategy(Strategy) {
  constructor(
    private readonly userService: UserService,
  ) {
    super({
      usernameField: 'username',
      passwordField: 'password',
    } as IStrategyOptions);
  }

  async validate(username: string, password: string): Promise<any> {
    
    const user = await this.userService.login(username, password)
    return user;
  }
}
  • 创建 jwt.contants.ts文件
    做验证
export const jwtContants = {
  secret: 'json_web_token_secret_key',
};
  • 创建 jwt.strategy.ts文件
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { jwtContants } from './jwt.contants';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { user } from './entity/user.entity';
// import 

// import { ConfigService } from '@nestjs/config';
// import { StrategyOptions, Strategy, ExtractJwt } from 'passport-jwt';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor() {
    super({
      // 获取请求header token值
      jwtFromRequest: ExtractJwt.fromHeader('token'),
      secretOrKey: jwtContants.secret,
    });
  }  
  async validate(payload: any) {
    console.log('payload', payload);
    //payload:jwt-passport认证jwt通过后解码的结果
    return { username: payload.username, id: payload.sub };
  }
}
  • 在登录接口位置使用 @UseGuards 装饰器
@UseGuards(AuthGuard('local')) //守卫将从body中提取username、password,然后调用LocalStrategy中的validate方法,若认证通过,则将User信息赋值给request.user。

  • 现在接口就能返回用户信息的token了

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值