You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Nest.js使用passport-local报错:Unknown authentication strategy 'local'求助

解决Nest.js中Passport-Local的Unknown authentication strategy "local"错误

问题1:根模块未导入AuthModule

你的AppModule没有导入AuthModule,导致LocalStrategy未被Nest的依赖注入容器实例化,Passport无法识别"local"策略。

修复后的app.module.ts:

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { AuthModule } from './auth/auth.module';

@Module({
  imports: [AuthModule],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

问题2:LocalStrategy的Injectable导入错误

local.strategy.ts中错误地从@angular/core导入Injectable,这是Angular框架的依赖,应替换为Nest的@nestjs/common包中的Injectable。

修复后的local.strategy.ts:

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

@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
    constructor(private authService: AuthService) {
        super();
    }

    async validate(username: string, password: string): Promise<any> {
        const user = await this.authService.validateUser(username, password);
        if (!user) {
            throw new UnauthorizedException();
        }
        return user;
    }
}

问题3:UsersService的existsUser方法逻辑错误

existsUser中Array.find的回调函数未返回判断结果,导致永远返回undefined,进而AuthService的validateUser会返回null触发未授权异常。

修复后的user.service.ts:

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

export type User = {
    id: number,
    name: string,
    username: string,
    password: string
}

@Injectable()
export class UsersService {
    private readonly users: User[] = [
        {
            id: 1,
            name: "testname",
            username: "cooluser",
            password: "admin"
        }
    ];

    async existsUser(username: string): Promise<User | undefined> {
        return this.users.find(user => user.username === username);
    }
}

内容的提问来源于stack exchange,提问作者gabri2503

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 04:15:27