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


You might also enjoy

16 New ML Gems for Ruby

Securing Sensitive Data in Rails

Introducing Dexter, the Automatic Indexer for Postgres


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