Nestjs 身份验证

Posted ajanuw

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Nestjs 身份验证相关的知识,希望对你有一定的参考价值。

文档

yarn add @nestjs/passport passport passport-http-bearer @nestjs/jwt passport-jwt

auth.service.ts

import { JwtService } from '@nestjs/jwt';
import { Injectable } from '@nestjs/common';
// import { UsersService } from '../users/users.service';

@Injectable()
export class AuthService {
  constructor(
    // private readonly usersService: UsersService,
    private readonly jwtService: JwtService,
  ) {}

  async signIn(): Promise<string> {
    // In the real-world app you shouldn't expose this method publicly
    // instead, return a token once you verify user credentials
    console.log(123)
    const user = { email: '[email protected]' };
    return this.jwtService.sign(user);
  }

  async validateUser(payload: any): Promise<any> {
    // return await this.usersService.findOneByEmail(payload.email);
    console.log(payload);
    return {};
  }
}

jwt.strategy.ts

import { ExtractJwt, Strategy } from 'passport-jwt';
import { AuthService } from './auth.service';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable, UnauthorizedException } from '@nestjs/common';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(private readonly authService: AuthService) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      secretOrKey: 'secretKey',
    });
  }

  async validate(payload: any) {
    const user = await this.authService.validateUser(payload);
    if (!user) {
      throw new UnauthorizedException();
    }
    return user;
  }
}

app.module.ts

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { PassportModule } from '@nestjs/passport';
import { JwtModule } from '@nestjs/jwt';
import { AuthService } from './auth.service';
import { JwtStrategy } from './jwt.strategy';

@Module({
  imports: [
    PassportModule.register({ defaultStrategy: 'jwt' }),
    JwtModule.register({
      secretOrPrivateKey: 'secretKey',
      signOptions: {
        expiresIn: 3600,
      },
    }),
  ],
  controllers: [AppController],
  providers: [AppService, AuthService, JwtStrategy],
})
export class AppModule {}

app.controller.ts

import { Get, Controller, UseGuards } from '@nestjs/common';
import { AppService } from './app.service';
import { Repository } from 'typeorm';
import { AuthGuard } from '@nestjs/passport';
import { AuthService } from './auth.service';

@Controller()
export class AppController {
  constructor(
    private readonly appService: AppService,
    private readonly authService: AuthService,
  ) {}

  @Get('token')
  async createToken(): Promise<any> {
    return await this.authService.signIn();
  }

  @Get('users')
  @UseGuards(AuthGuard())
  users(): any {
    return [1];
  }
}

先获取token,在每次请求中发送token

λ curl localhost:5000/token
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6InVzZXJAZW1haWwuY29tIiwiaWF0IjoxNTQzMDc0NDU1LCJleHAiOjE1NDMwNzgwNTV9.jtfgp3XxHT20h83k24Ukk0TgtYqGWZaCglUdtbVFmF4

λ curl localhost:5000/users -H "authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWF
pbCI6InVzZXJAZW1haWwuY29tIiwiaWF0IjoxNTQzMDc0NDU1LCJleHAiOjE1NDMwNzgwNTV9.jtfgp3XxHT20h83k24Ukk0Tgt YqGWZaCglUdtbVFmF4"
[1]


λ curl localhost:5000/users -H "authorization: Bearer 123"
{"statusCode":401,"error":"Unauthorized"}

以上是关于Nestjs 身份验证的主要内容,如果未能解决你的问题,请参考以下文章

NestJs 使用 jwt 和私钥和公钥进行身份验证

NestJs套接字身份验证,在handleConnection中发出事件

NestJS 在 e2e 测试中模拟 JWT 身份验证

Nestjs 身份验证

使用电子邮件进行身份验证时,NestJS 护照身份验证返回 401

NestJs JWT 身份验证返回 401