Method: Twilio::Security::RequestValidator#validate

Defined in:
lib/twilio-ruby/security/request_validator.rb

#validate(url, params, signature) ⇒ Boolean

Validates that after hashing a request with Twilio’s request-signing algorithm (www.twilio.com/docs/usage/security#validating-requests), the hash matches the signature parameter

Parameters:

  • url (String)

    The url sent to your server, including any query parameters

  • params (String, Hash, #to_unsafe_h)

    In most cases, this is the POST parameters as a hash. If you received a bodySHA256 parameter in the query string, this parameter can instead be the POST body as a string to validate JSON or other text-based payloads that aren’t x-www-form-urlencoded.

  • signature (String)

    The expected signature, from the X-Twilio-Signature header of the request

Returns:

  • (Boolean)

    whether or not the computed signature matches the signature parameter



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/twilio-ruby/security/request_validator.rb', line 27

def validate(url, params, signature)
  parsed_url = URI(url)
  url_with_port = add_port(parsed_url)
  url_without_port = remove_port(parsed_url)

  valid_body = true # default succeed, since body not always provided
  params_hash = body_or_hash(params)
  unless params_hash.is_a? Enumerable
    body_hash = URI.decode_www_form(parsed_url.query || '').to_h['bodySHA256']
    params_hash = build_hash_for(params)
    valid_body = !(params_hash.nil? || body_hash.nil?) && secure_compare(params_hash, body_hash)
    params_hash = {}
  end

  # Check signature of the url with and without port numbers
  # since signature generation on the back end is inconsistent
  valid_signature_with_port = secure_compare(build_signature_for(url_with_port, params_hash), signature)
  valid_signature_without_port = secure_compare(build_signature_for(url_without_port, params_hash), signature)

  valid_body && (valid_signature_with_port || valid_signature_without_port)
end