首页 > 解决方案 > Nest.js 使用 typeORM 进行身份验证

问题描述

我创建了一个连接到数据库的工作服务器,一个简单的get请求可以工作。我遵循了https://docs.nestjs.com/techniques/authentication本指南。

当运行服务器并尝试get从受保护的路由执行请求时,我得到Cannot read property 'challenge' of undefined.

用户控制器.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] In order to use "defaultStrategy", please, ensure to import PassportModule in each place where AuthGuard() is being used. Otherwise, passport won't work correctly.

标签: typescriptpassport.jsnestjstypeorm

解决方案


推荐阅读