nestjs添加JWT

发布于 23 天前  30 次阅读


1. 用户逻辑处理

async validateUser(username, password) {
    const user = await this.userService.findUser(username);
    if (user && user.password === password) {
      const { password, ...result } = user;
      return result;
    }
    return '用户不存在';
  }

2.获取token

// auth.module.ts
JwtModule.register({
      secret: jwtConstants.secret,
      signOptions: {
        expiresIn: '6000s',
      },
    }),
async login(user: any) {
    const payload = { username: user.username, sub: user.userId };
    return {
      access_token: this.jwtService.sign(payload),
    };
  }

3. 验证token

// jwt.strategy.ts
import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable } from '@nestjs/common';
import { jwtConstants } from './constants';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor() {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: jwtConstants.secret,
    });
  }

  async validate(payload: any) {
      console.log(1, payload);

      console.log(`JWT验证 - Step 4: 被守卫调用`, payload);
    return { userId: payload.sub, username: payload.username };
  }
}

// jwt-auth.guard.ts
import {
  ExecutionContext,
  Injectable,
  UnauthorizedException,
} from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';

@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {
  canActivate(context: ExecutionContext) {
    // Add your custom authentication logic here
    // for example, call super.logIn(request) to establish a session.
    return super.canActivate(context);
  }

  handleRequest(err, user, info) {
    console.log(1112, user, info);

    // You can throw an exception based on either "info" or "err" arguments
    if (err || !user) {
      throw err || new UnauthorizedException();
    }
    return user;
  }
}

// user.contriller.ts
@UseGuards(JwtAuthGuard)
  @Get()
  find(@Query() query) {
    return this.authService.login(query)
  }


我们总是担心自己不够好,殊不知,当我们踏出去的时候,便是
最好的自己