Access raw body of Stripe webhook in Nest.js

后端 未结 4 1747
抹茶落季
抹茶落季 2021-02-03 11:36

I need to access the raw body of the webhook request from Stripe in my Nest.js application.

Following this example, I added the below to the module which has a controlle

4条回答
  •  天命终不由人
    2021-02-03 12:18

    I ran into a similar problem last night trying to authenticate a Slack token.

    The solution we wound up using did require disabling the bodyParser from the core Nest App then re-enabling it after adding a new rawBody key to the request with the raw request body.

        const app = await NestFactory.create(AppModule, {
            bodyParser: false
        });
    
        const rawBodyBuffer = (req, res, buf, encoding) => {
            if (buf && buf.length) {
                req.rawBody = buf.toString(encoding || 'utf8');
            }
        };
    
        app.use(bodyParser.urlencoded({verify: rawBodyBuffer, extended: true }));
        app.use(bodyParser.json({ verify: rawBodyBuffer }));
    
    

    Then in my middleware I could access it like so:

    const isVerified = (req) => {
        const signature = req.headers['x-slack-signature'];
        const timestamp = req.headers['x-slack-request-timestamp'];
        const hmac = crypto.createHmac('sha256', 'somekey');
        const [version, hash] = signature.split('=');
    
        // Check if the timestamp is too old
        // tslint:disable-next-line:no-bitwise
        const fiveMinutesAgo = ~~(Date.now() / 1000) - (60 * 5);
        if (timestamp < fiveMinutesAgo) { return false; }
    
        hmac.update(`${version}:${timestamp}:${req.rawBody}`);
    
        // check that the request signature matches expected value
        return timingSafeCompare(hmac.digest('hex'), hash);
    };
    
    export async function slackTokenAuthentication(req, res, next) {
        if (!isVerified(req)) {
            next(new HttpException('Not Authorized Slack', HttpStatus.FORBIDDEN));
        }
        next();
    }
    

    Shine On!

提交回复
热议问题