Sku*_*ter 11 authentication passport-local passport.js nestjs nestjs-passport
我正在尝试实施护照本地策略,但验证方法不起作用。当我这样做时@UseGuards(AuthGuard("local")),它会自动抛出未经授权的异常,而无需通过我编写的验证方法。我不知道我做错了什么,因为文档也做了同样的事情。
这是我的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;
}
}
Run Code Online (Sandbox Code Playgroud)
我的AuthModule导入:
@Module({
imports: [TypeOrmModule.forFeature([UserRepository]), PassportModule],
controllers: [AuthController],
providers: [AuthService, LocalStrategy],
})
export class AuthModule {}
Run Code Online (Sandbox Code Playgroud)
用法示例:
@Post("/login")
@UseGuards(LocalAuthGuard)
async login(@Body() loginDto: LoginDto) {
return this.authService.login(loginDto);
}
Run Code Online (Sandbox Code Playgroud)
Jay*_*iel 28
在花费更多时间编写代码并自己进行深入研究之后,事实上该方法必须具有名为和 的validate参数,它们可以是和,但重要的是您有两个属性和。如果你没有和,那么你将永远无法进入班级。 usernamepasswordbobalicereq.bodyusernamepasswordreq.body.usernamereq.body.passwordvalidateLocalStrategy
该validate方法必须具有参数username,password 并且/或参数必须与构造函数中传递的usernameField和值匹配。如果它们不匹配,则不会调用该方法。我认为这是由于 Nest 打电话的事实,但我不能 100% 确定。passwordFieldsuper()validatevalidate(...args)
| 归档时间: |
|
| 查看次数: |
7449 次 |
| 最近记录: |