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"}

猜你喜欢

转载自www.cnblogs.com/ajanuw/p/10014199.html