【问题标题】:How do I exclude routing validation in nest.js?如何在 nest.js 中排除路由验证?
【发布时间】:2020-12-11 17:18:19
【问题描述】:

// jwt guard

@UseGuards(AuthStrategyGuard)
@Controller('users')
export class UsersController {
  constructor(private readonly authService: AuthService, private readonly usersService: UsersService) {}
  @Post()
  async getIndex (@Body() body) {
    if (!body.user) {
      throw new UnauthorizedException('error auth');
    } else {
      const token = await this.authService.sign(body);
      return { token }
    }
  }
  @Post('auth')
  validating (@Body('token') token) {
    console.log(token, 'token');
    return {success: 1}
  }
  @Post('test')
  getTestIndex () {
    return {success: 1}
  }
}

这里是 JSONWebToken 验证逻辑

我想从 JWT 验证中排除 @post () 装饰器

我该怎么办?

【问题讨论】:

    标签: javascript node.js nestjs


    【解决方案1】:

    您可以通过仅在您需要验证的方法(端点)上应用防护来做到这一点,在您的情况下,它将是:(我假设您想从第一条路线中排除验证

    @Controller('users')
    export class UsersController {
      constructor(private readonly authService: AuthService, private readonly usersService: UsersService) {}
      
      @Post()
      async getIndex (@Body() body) {
        if (!body.user) {
          throw new UnauthorizedException('error auth');
        } else {
          const token = await this.authService.sign(body);
          return { token }
        }
      }
      @UseGuards(AuthStrategyGuard)
      @Post('auth')
      validating (@Body('token') token) {
        console.log(token, 'token');
        return {success: 1}
      }
       @UseGuards(AuthStrategyGuard)
      @Post('test')
      getTestIndex () {
        return {success: 1}
      }
    }
    

    【讨论】:

    • 我使用自定义装饰器实现了这个想法,使用了applyDecorators 方法
    猜你喜欢
    • 2016-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-09
    • 2019-08-15
    • 2021-09-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多