gpt4 book ai didi

nestjs - 在 Guard 中访问请求的原始正文?

转载 作者:行者123 更新时间:2023-12-04 17:29:27 26 4
gpt4 key购买 nike

有没有办法访问请求的原始正文?不是已经解析成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.
}
}

最佳答案

Shopify 有一个类似的方法来验证请求,这段代码对我有用,也许你可以改变它。

首先你需要安装加密:

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");
}
}
}

最后在您的 Controller 上:
@Post()
@UseGuards(ShopifyAuthGuard)
async createNewOrder(@Body() orderDto: OrderDto) {}

希望能帮助到你!

关于nestjs - 在 Guard 中访问请求的原始正文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61070302/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com