【发布时间】:2021-12-15 16:38:13
【问题描述】:
这些是我拥有的部分 NestJS 代码 sn-ps。我正在尝试实施护照本地策略来获取用户名和密码。我收到 -Error: Unknown authentication strategy "local", in the controller file when using the auth guard.
AuthModule.ts
import { Module } from '@nestjs/common';
import { JwtModule } from '@nestjs/jwt';
import { PassportModule } from '@nestjs/passport';
import { UserModule } from 'src/user/user.module';
import { JwtAuthController } from './jwt-auth.controller';
import { JwtAuthService } from './jwt-auth.service';
import { JwtStrategy } from './jwt.strategy';
import { LocalStrategy } from './local.strategy';
@Module({
imports: [
UserModule,
PassportModule,
JwtModule.register({
secret: process.env.SECRETKEY,
signOptions: { expiresIn: '3600s' }
})
],
controllers: [JwtAuthController],
providers: [JwtAuthService, LocalStrategy, JwtStrategy],
exports: [JwtAuthService],
})
export class JwtAuthModule {}
local.strategy.ts
import { Strategy } from 'passport-local';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { JwtAuthService } from './jwt-auth.service';
@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy, 'local') {
constructor(private authService: JwtAuthService) {
super();
}
async validate(username: string, password: string): Promise<any> {
const user = await this.authService.validateUser({username, password});
if (!user) {
throw new UnauthorizedException();
}
return user;
}
}
app.controller.ts
import { Body, Controller, Get, Post, Req, UnauthorizedException, UseGuards } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { JwtAuthService } from './jwt-auth/jwt-auth.service';
@Controller()
export class AppController {
constructor(private readonly authService: JwtAuthService) {}
@UseGuards(AuthGuard('local'))
@Post('/auth/login')
async login(@Req() req) {
return this.authService.login(req.user)
}
}
我在调用 /auth/login API 时收到以下错误
[Nest] 26753 - 10/31/2021, 22:08:18 ERROR [ExceptionsHandler] Unknown authentication strategy "local"
Error: Unknown authentication strategy "local"
我错过了什么吗?提前致谢。
【问题讨论】:
-
AppController生活在哪个模块中? -
AppController 在 app.module.ts 中。我已经从 auth.module 导出了 auth.service.ts 并且 auth.module 被导入到了 app.module.ts
-
你的
JwtAuthServiceREQUEST是作用域吗? -
我是 NESTjs 的新手。如何确定 JwtAuthService REQUEST 是否有范围?
-
尝试将
AuthModule添加到app.module.ts的导入中。
标签: javascript authentication passport.js nestjs passport-local