无法使用 PassportJS 读取未定义、NestJS 的属性“validateUser”
Posted
技术标签:
【中文标题】无法使用 PassportJS 读取未定义、NestJS 的属性“validateUser”【英文标题】:Cannot read property 'validateUser' of undefined ,NestJS using PassportJS 【发布时间】:2021-05-03 12:05:12 【问题描述】:我只想在 NestJS 中通过 passportjs 实现身份验证。 当我向“localhost:3000/auth/login”发送帖子请求时出现这些错误。
[ExceptionsHandler] Cannot read property 'validateUser' of undefined
TypeError: Cannot read property 'validateUser' of undefined
这是我的代码:
local.strategy.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
app.controller.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,但出现错误。 我该如何解决这个问题?
【问题讨论】:
【参考方案1】:将@Injectable()
添加到LocalStrategy
类。
【讨论】:
太酷了兄弟 :)【参考方案2】:手动删除 dist 文件夹并重新启动服务器对我有用
【讨论】:
以上是关于无法使用 PassportJS 读取未定义、NestJS 的属性“validateUser”的主要内容,如果未能解决你的问题,请参考以下文章
Express Passportjs在路由器回调中未进行身份验证
为啥 Node 中的 PassportJS 不会在注销时删除会话