首页 > 解决方案 > 无法使用 PassportJS 读取未定义、NestJS 的属性“validateUser”

问题描述

我只想在 NestJS 中通过 passportjs 实现身份验证。当我将发布请求发送到“localhost:3000/auth/login”时,我收到了这些错误行。

[ExceptionsHandler] Cannot read property 'validateUser' of undefined
TypeError: Cannot read property 'validateUser' of undefined

这是我的代码:

本地策略.ts

import { AuthService } from './auth.service';
import { PassportStrategy } from '@nestjs/passport';
import { Strategy } from 'passport-local';
import { UnauthorizedException } from '@nestjs/common';

export class LocalStrategy extends PassportStrategy(Strategy) {
  constructor(private authService: AuthService) {
    super();
  }
  async validate(username: string, password: string): Promise<any> {
    console.log(username, password);
    const user = await this.authService.validateUser(username, password); <====This part
    if (!user) {
      return new UnauthorizedException();
    }
    return user;
  }
}

auth.service.ts

import { Injectable } from '@nestjs/common';

@Injectable()
export class AuthService {
  users = [{ id: 1, username: 'Peyman', password: 'password' }];
  async validateUser(username: string, password: string): Promise<any> {
    console.log('Validate');
    const user = await this.users.find((x) => x.username === username);
    if (user && user.password === password) {
      return user;
    }
    return null;
  }
}

auth.module.ts

import { LocalStrategy } from './local.strategy';
import { Module } from '@nestjs/common';
import { PassportModule } from '@nestjs/passport';
import { AuthService } from './auth.service';

@Module({
  imports: [PassportModule],
  providers: [AuthService, LocalStrategy],
  exports: [PassportModule],
})
export class AuthModule {}

app.module.ts

import { Contact } from './contacts/contacts.entity';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Module } from '@nestjs/common';
import { ContactsModule } from './contacts/contacts.module';
import { AppController } from './app.controller';
import { AuthModule } from './auth/auth.module';
import { PassportModule } from '@nestjs/passport';

@Module({
  imports: [
    ContactsModule,
    PassportModule,
    TypeOrmModule.forRoot({ entities: [Contact] }),
    AuthModule,
  ],
  controllers: [AppController],
  providers: [],
})
export class AppModule {}

应用程序控制器.ts

import { Controller, Post, UseGuards, Request } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';

@Controller()
export class AppController {
  @UseGuards(AuthGuard('local'))
  @Post('auth/login')
  public async login(@Request() req): Promise<any> {
    return req.user;
  }
}

我通过依赖注入注入authservice,但出现错误。我怎样才能解决这个问题?

标签: typescriptpassport.jsnestjs

解决方案


添加@Injectable()LocalStrategy类。


推荐阅读