Доступ к сырому телу запроса в гвардии? - PullRequest
0 голосов
/ 07 апреля 2020

Есть ли способ получить доступ к необработанному телу запроса? Не то, что было проанализировано в json?

@Injectable()
export class WooGuard implements CanActivate {
  secret: string;

  constructor(
    private readonly reflector: Reflector,
    private configService: ConfigService,
    ) {
      this.secret = this.configService.get<string>("woocommerce.webhook.secret");
    }

  async canActivate(
    context: ExecutionContext,
    ): Promise<boolean> {

    const request = context.switchToHttp().getRequest<Request>();
    request.body // this is parsed json

    // I am calculating the sha256 hash of the body with a secret for a webhook.
    // due to how the raw json is vs. the JSON.stringify(request.body), the signature is never the same.
  }
}

1 Ответ

0 голосов
/ 07 апреля 2020

Shopify имеет аналогичный способ проверки запросов, этот код работал для меня, возможно, вы можете изменить его.

Сначала вам нужно установить crypto:

npm install --save crypto

Затем:

import { Injectable, CanActivate, ExecutionContext, HttpStatus } from '@nestjs/common';
const crypto = require('crypto');

@Injectable()
export class ShopifyAuthGuard implements CanActivate {
  async canActivate(context: ExecutionContext): Promise<boolean> {
    const request = context.switchToHttp().getRequest();
    const secretKey = <MY_KEY>;

    const hmac = request.headers["x-shopify-hmac-sha256"];

    const hash = crypto
      .createHmac('sha256', secretKey)
      .update(request.body)
      .digest('base64');

    if (hmac === hash) {
      return true;
    } else {
      throw new ForbiddenException("Not allowed");
    }
  }
}

И, наконец, на вашем контроллере:

@Post()
@UseGuards(ShopifyAuthGuard)
async createNewOrder(@Body() orderDto: OrderDto) {}

Надеюсь, это поможет!

...