ruby
41 lines · 7 steps
Signing and verifying webhooks in Ruby
An HMAC-based scheme that binds a timestamp to each payload and rejects stale or tampered requests.
Explained by
highlit
1require "openssl"
2require "base64"
3
4module WebhookSignature
5 DEFAULT_TOLERANCE = 300
6
7 module_function
8
9 def sign(payload, secret, timestamp: Time.now.to_i)
10 digest = compute(payload, secret, timestamp)
11 "t=#{timestamp},v1=#{digest}"
12 end
13
14 def verify(payload, header, secret, tolerance: DEFAULT_TOLERANCE)
15 parts = parse(header)
16 timestamp = Integer(parts.fetch("t"))
17 provided = parts.fetch("v1")
18
19 raise "timestamp outside tolerance" if (Time.now.to_i - timestamp).abs > tolerance
20
21 expected = compute(payload, secret, timestamp)
22 unless OpenSSL::Utils.secure_compare(expected, provided)
23 raise "signature mismatch"
24 end
25
26 true
27 end
28
29 def compute(payload, secret, timestamp)
30 signed = "#{timestamp}.#{payload}"
31 raw = OpenSSL::HMAC.digest("SHA256", secret, signed)
32 Base64.urlsafe_encode64(raw, padding: false)
33 end
34
35 def parse(header)
36 header.split(",").each_with_object({}) do |pair, acc|
37 key, value = pair.strip.split("=", 2)
38 acc[key] = value
39 end
40 end
41end
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Including a timestamp in the signed material lets you reject replayed requests with a tolerance window.
- 2Signatures must be checked with a constant-time comparison to avoid leaking information through timing.
- 3Centralizing the signed-string format in one helper keeps signing and verifying provably in sync.
Related explainers
ruby
class CartMergeService def initialize(guest_cart:, user_cart:) @guest_cart = guest_cart @user_cart = user_cart
Merging a guest cart into a user cart in Rails
service object
transactions
idempotency
Intermediate
7 steps
ruby
require 'monitor' class TokenBucket include MonitorMixin
A thread-safe token bucket rate limiter in Ruby
rate-limiting
concurrency
thread-safety
Intermediate
8 steps
ruby
class Product < ApplicationRecord belongs_to :account after_save :record_audit_trail
Building an audit trail with Rails callbacks
callbacks
audit-logging
dirty-tracking
Intermediate
7 steps
ruby
class User < ApplicationRecord store_accessor :preferences, :theme, :timezone,
Storing user settings in a JSON column with Rails
store_accessor
json-columns
validations
Intermediate
7 steps
ruby
require "time" require "tzinfo" module TimeConverter
Converting timestamps across time zones with TZInfo
timezones
iso8601
parsing
Intermediate
8 steps
ruby
class Subscription < ApplicationRecord belongs_to :account enum :status, {
Modeling subscription lifecycle in Rails
enums
scopes
state-management
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/signing-and-verifying-webhooks-in-ruby-explained-ruby-0079/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.