ค้นหาเว็บไซต์

typescript - การยืนยันตัวตนใน Nest.js โดยใช้ typeORM


ฉันได้สร้างเซิร์ฟเวอร์ที่ทำงานได้พร้อมการเชื่อมต่อกับฐานข้อมูลแล้ว พร้อมคำขอ get แบบง่ายที่ทำงานได้ ฉันได้ทำตามคู่มือนี้ https://docs.nestjs.com/techniques/authentication

เมื่อรันเซิร์ฟเวอร์และพยายามทำคำขอ get จากเส้นทางที่มีการป้องกัน ฉันได้รับข้อความ Cannot read property 'challenge' of undefined.

user.controller.ts

import { Controller, Get, UseGuards } from '@nestjs/common';
import { UserService } from './user.service';
import { User } from './user.entity';
import { AuthGuard, PassportModule } from '@nestjs/passport';

@Controller()
export class UserController {
  constructor(
    private readonly userService: UserService)
    {}

  @Get('user')
  @UseGuards(AuthGuard())
  findAll(): Promise<User[]> {
   return this.userService.findAll();
  }

  @Get('users')
  find(): Promise<User[]> {
   return this.userService.findAll();
  }
}

auth.module.ts

import { Module } from '@nestjs/common';
import { AuthService } from './auth.service';
import { HttpStrategy } from './http.strategy';
import { UserModule } from 'database/entities/user/user.module';
import { PassportModule } from '@nestjs/passport';
const passportModule = PassportModule.register({ defaultStrategy: 'bearer' });

@Module({
  imports: [
    passportModule,
    UserModule],
    providers: [AuthService, HttpStrategy],
    exports: [passportModule],
})
export class AuthModule {}

นอกจากนี้เมื่อรันเซิร์ฟเวอร์ฉันได้รับคำเตือน [AuthGuard] เพื่อใช้ "defaultStrategy" กรุณาให้แน่ใจว่าคุณได้ทำการ import PassportModule ในทุกที่ที่มีการใช้งาน AuthGuard() มิฉะนั้น passport จะไม่ทำงานอย่างถูกต้อง