无法在Google云功能中验证Twilio请求 [英] Unable to validate Twilio request in Google cloud function

查看:52
本文介绍了无法在Google云功能中验证Twilio请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有Google云功能,Twilio向其发送具有SMS状态的POST请求,但是我无法使用

I have a Google cloud function to which Twilio sends POST requests with SMS statuses but I am unable to verify that the requests are coming from Twilio using any of the methods outlined in https://www.twilio.com/docs/usage/security

我的第一次尝试是使用validateRequest函数,如下面的代码所示

My first attempt consisted of using the validateRequest function, as shown in the code below

const twilio = require('twilio');

let url = 'https://....cloudfunctions.net/...'
let token = 'XXXX';
let header = request.headers['x-twilio-signature'];
let sortedKeys = Object.keys(request.body).sort();
let sortedParams = {};

sortedKeys.forEach(key => {
  sortedParams[key] = request.body[key];
});

let validated = twilio.validateRequest(token, header, url, sortedParams);

我确认令牌的值与Twilio帐户设置中的auth令牌匹配,sortedParams包含按字母顺序排序的驼峰式Twilio请求参数,并且URL与创建SMS时传递给Twilio客户端的URL匹配.但是,validateRequest总是返回false.

I confirmed that the value of token matched the auth token from the Twilio account settings, sortedParams contained alphabetically sorted camel-cased Twilio request params and the url matched that which was passed to the Twilio client when creating the SMS. However, validateRequest would always return false.

我的下一个尝试是通过从

My next attempt involved hashing the combination of the url and request params by copying the code from https://www.twilio.com/docs/libraries/reference/twilio-node/3.18.0/webhooks_webhooks.js.html

const crypto = require('crypto')

sortedKeys.forEach(key => {
  url = `${url}${key}${request.body[key]}`;
});

let signature = crypto
    .createHmac('sha1', token)
    .update(Buffer.from(url, 'utf-8'))
    .digest('base64');

在将签名的值与标头的值进行比较时,两者从未匹配.

Upon comparing the value of signature to that of the header, the two never matched.

推荐答案

事实证明validateRequest并没有什么问题,而是我声明令牌的方式.它不是从函数代码中进行硬编码,而是从Google存储桶中检索它作为缓冲区,然后转换为字符串.由于未知原因,即使在视觉上,检索到的值与原始标记匹配,===比较也返回false.一旦我对令牌进行了硬编码,一切都会正常工作.

It turns out that the there was nothing wrong with the validateRequest but rather the way I was declaring the token. Instead of hard-coding it in the function's code, it was being retrieved from a Google storage bucket as a buffer and then converted to a string. For unknown reasons, even though visually, the retrieved value matched the original token, a === comparison returned false. Once I hard-coded the token, everything worked.

这篇关于无法在Google云功能中验证Twilio请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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