Verify Slack Requests in Rails

Slack signs its requests so you can verify they’re authentic.

Here’s a method you can use in your Rails controllers for it.

def request_verified?
  timestamp = request.headers["X-Slack-Request-Timestamp"]
  signature = request.headers["X-Slack-Signature"]
  signing_secret = ENV.fetch("SLACK_SIGNING_SECRET")

  if Time.at(timestamp.to_i) < 5.minutes.ago
    return false # expired
  end

  basestring = "v0:#{timestamp}:#{request.body.read}"
  my_signature = "v0=#{OpenSSL::HMAC.hexdigest("SHA256", signing_secret, basestring)}"

  ActiveSupport::SecurityUtils.secure_compare(my_signature, signature)
end

lock

Published September 14, 2018 · Tweet


You might also enjoy

Securing Sensitive Data in Rails

Introducing Dexter, the Automatic Indexer for Postgres

Rails, Meet Data Science


All code examples are public domain.
Use them however you’d like (licensed under CC0).