NestJS和Passport-local:AuthGuard('local&39;)valify()从不被调用 [英] NestJS and passport-local : AuthGuard('local') validate() never get called

查看:23
本文介绍了NestJS和Passport-local:AuthGuard('local&39;)valify()从不被调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经一步一步地关注了Nest官方文档(https://docs.nestjs.com/security/authentication),但在登录操作中使用@AuthGuard(‘local’)或@AuthGuard(LocalAuthGuard)时无法调用Validation()方法。

如果我不使用防护装饰器,所有工作都将按预期进行(但我需要使用它将令牌添加到请求对象)。

auth.controller.ts

  @UseGuards(AuthGuard('local')) // or AuthGuard(LocalAuthGuard)
  @Post('login')
  async login(
    @Request() req
  ) {
    const { access_token } = await this.authService.login(req.user);
    return access_token;
  }
}

local.strategy.ts

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

  async validate(email: string, password: string): Promise<any> { // class is constructed but this method is never called
    const user: UserDto = await this.authService.login({
      email,
      password,
    });
    
    if (!user) {
      throw new UnauthorizedException();
    }
    return user;
  }
}

auth.module.ts

@Module({
  imports: [
    UsersModule,
    PassportModule,
    JwtModule.register({
      secret: "bidon", 
      signOptions: {
        expiresIn: '3600',
      },
    }),
  ],
  providers: [AuthService, LocalStrategy, JwtStrategy],
  exports: [AuthService, PassportModule, JwtModule],
  controllers: [AuthController],
})
export class AuthModule {}

PS:我已经阅读了所有与堆栈溢出相关的帖子(例如:NestJS' Passport Local Strategy "validate" method never called),但它们对我没有帮助。

推荐答案

我发现,如果我们不传递emailpassword这两个错误的值,防护将响应未经授权消息。问题是,如果未定义必填字段,即前端不会将其传递给服务器,如何确保在运行防护逻辑之前对其进行验证。如果我们在控制器方法中添加@Body() data: loginDto,它将不会验证正文参数。

为了解决这个问题,我在local.guard.ts文件中添加了一些验证代码。以下是我的项目中的代码:

import { HttpException, HttpStatus, Injectable, UnauthorizedException } from "@nestjs/common";
import { AuthGuard } from "@nestjs/passport";

@Injectable()
export class LocalAuthGuard extends AuthGuard('local') {
  handleRequest(err, user, info, context, status) {
    const request = context.switchToHttp().getRequest();
    const { mobile, password } = request.body;
    if (err || !user) {
      if (!mobile) {
        throw new HttpException({ message: '手机号不能为空' }, HttpStatus.OK);
      } else if (!password) {
        throw new HttpException({ message: '密码不能为空' }, HttpStatus.OK);
      } else {
        throw err || new UnauthorizedException();
      }
    }
    return user;
  }
}

这篇关于NestJS和Passport-local:AuthGuard(&#39;local&39;)valify()从不被调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆