class Rack::RestcommWebhookAuthentication

Middleware that authenticates webhooks from Restcomm 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::RestcommWebhookAuthentication, 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/restcomm_webhook_authentication.rb
20 def initialize(app, auth_token, *paths, &auth_token_lookup)
21   @app = app
22   @auth_token = auth_token
23   define_singleton_method(:get_auth_token, auth_token_lookup) if block_given?
24   @path_regex = Regexp.union(paths)
25 end

Public Instance Methods

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