用于验证传入的 Twilio 请求的装饰器

我试图遵循这个非常直接的指南,了解如何防止非 twilio 请求访问我为传入的 twilio 消息设置的 webhook url。它基本上涉及复制他们作为装饰器开发的功能,并将其应用于处理传入消息的视图。


https://www.twilio.com/docs/usage/tutorials/how-to-secure-your-django-project-by-validating-incoming-twilio-requests


from django.http import HttpResponse, HttpResponseForbidden

from functools import wraps

from twilio import twiml

from twilio.request_validator import RequestValidator


import os



def validate_twilio_request(f):

    """Validates that incoming requests genuinely originated from Twilio"""

    @wraps(f)

    def decorated_function(request, *args, **kwargs):

        # Create an instance of the RequestValidator class

        validator = RequestValidator(os.environ.get('TWILIO_AUTH_TOKEN'))


        # Validate the request using its URL, POST data,

        # and X-TWILIO-SIGNATURE header

        request_valid = validator.validate(

            request.build_absolute_uri(),

            request.POST,

            request.META.get('HTTP_X_TWILIO_SIGNATURE', ''))


        # Continue processing the request if it's valid, return a 403 error if

        # it's not

        if request_valid:

            return f(request, *args, **kwargs)

        else:

            return HttpResponseForbidden()

    return decorated_function

慕后森
浏览 102回答 1
1回答

米琪卡哇伊

似乎RequestValidator不接受无。这应该修复它:validator = RequestValidator(os.environ.get('TWILIO_AUTH_TOKEN', ''))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python