class Rack::TwilioWebhookAuthentication

Middleware that authenticates webhooks from Twilio using the request validator.

The middleware takes an auth token with which to set up the request validator and any number of paths. When a path matches the incoming request path, the request will be checked for authentication.

Example:

require 'rack' use Rack::TwilioWebhookAuthentication, ENV, //messages/

The above appends this middleware to the stack, using an auth token saved in the ENV and only against paths that match //messages/. If the request validates then it gets passed on to the action as normal. If the request doesn't validate then the middleware responds immediately with a 403 status.

Public Class Methods

new(app, auth_token, *paths, &auth_token_lookup) click to toggle source
   # File lib/rack/twilio_webhook_authentication.rb
22 def initialize(app, auth_token, *paths, &auth_token_lookup)
23   @app = app
24   @auth_token = auth_token
25   define_singleton_method(:get_auth_token, auth_token_lookup) if block_given?
26   @path_regex = Regexp.union(paths)
27 end

Public Instance Methods

call(env) click to toggle source
   # File lib/rack/twilio_webhook_authentication.rb
29 def call(env)
30   return @app.call(env) unless env['PATH_INFO'].match(@path_regex)
31   request = Rack::Request.new(env)
32   original_url = request.url
33   params = request.post? ? request.POST : {}
34   auth_token = @auth_token || get_auth_token(params['AccountSid'])
35   validator = Twilio::Security::RequestValidator.new(auth_token)
36   signature = env['HTTP_X_TWILIO_SIGNATURE'] || ''
37   if validator.validate(original_url, params, signature)
38     @app.call(env)
39   else
40     [
41       403,
42       { 'Content-Type' => 'text/plain' },
43       ['Twilio Request Validation Failed.']
44     ]
45   end
46 end