1

Passport Local Strategy を実装しようとしていますが、validate メソッドが機能しません。@UseGuards(AuthGuard("local")) を実行すると、作成した検証メソッドを経由せずに Unauthorized Exception が自動的にスローされます。ドキュメントが同じことをしたので、何が間違っているのかわかりません。

私の LocalStrategy クラスは次のとおりです。

@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
  constructor(@InjectRepository(UserRepository) private userRepository: UserRepository) {
    super();
  }

  async validate(credentials: string, password: string): Promise<User> {
    // this method is never called, I've already did some console.logs
    const user = await this.userRepository.findByCredentials(credentials);

    if (!user) throw new UnauthorizedException("Invalid credentials");

    if (!(await argon2.verify(user.hash, password))) throw new UnauthorizedException("Invalid credentials");

    return user;
  }
}

私の AuthModule インポート:

@Module({
  imports: [TypeOrmModule.forFeature([UserRepository]), PassportModule],
  controllers: [AuthController],
  providers: [AuthService, LocalStrategy],
})
export class AuthModule {}

使用例:

  @Post("/login")
  @UseGuards(LocalAuthGuard)
  async login(@Body() loginDto: LoginDto) {
    return this.authService.login(loginDto);
  }
4

2 に答える 2

0

LocalAuthGuardここでクラスが欠落しているようです。このクラスでファイルを作成してから..

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

@Injectable()
export class LocalAuthGuard extends AuthGuard('local') {}

これにより、ローカル ガードが使用されます。

于 2021-06-29T03:20:45.480 に答える