Python Requires Chilkat v11.5.0+
Chilkat2-Python
Box: Verify a Captured V2 Webhook Signature
See more Box Examples
Verify raw payload bytes and captured headers using the configured primary and secondary signing keys. The example rejects stale/future timestamps and compares randomized HMACs of the signatures to avoid exposing a signature-prefix timing comparison. It does not host an HTTP listener. The receiver must persist/deduplicate the verified event and acknowledge promptly.
See the Box API guide for setup and the complete workflow.
Chilkat Python Downloads
import sys
import chilkat2
success = False
# Requires Chilkat 11.5.0 or later and a previously unlocked Chilkat bundle.
# See Global Unlock Sample.
# Guide: Box API Guide.
success = False
# Save the exact HTTP body bytes to this file, without JSON reserialization.
rawBody = chilkat2.BinData()
success = rawBody.LoadFile("qa_data/box_webhook_body.bin")
if (success != True):
print(rawBody.LastErrorText)
sys.exit()
# Read these fields case-insensitively from the incoming request headers.
# For this offline example, enter the captured header values.
timestamp = "BOX_DELIVERY_TIMESTAMP"
primarySignature = "BOX_SIGNATURE_PRIMARY"
secondarySignature = "BOX_SIGNATURE_SECONDARY"
signatureVersion = "1"
signatureAlgorithm = "HmacSHA256"
# Retrieve configured keys from protected application configuration.
primaryKey = "BOX_PRIMARY_SIGNATURE_KEY"
secondaryKey = "BOX_SECONDARY_SIGNATURE_KEY"
if ((signatureVersion != "1") or (signatureAlgorithm != "HmacSHA256")):
print("Unsupported signature version or algorithm.")
sys.exit()
delivered = chilkat2.CkDateTime()
success = delivered.SetFromTimestamp(timestamp)
if (success != True):
print(delivered.LastErrorText)
sys.exit()
now = chilkat2.CkDateTime()
success = now.SetFromCurrentSystemTime()
if (success != True):
print(now.LastErrorText)
sys.exit()
age = int(now.GetAsUnixTime(False)) - int(delivered.GetAsUnixTime(False))
# Box recommends rejecting deliveries older than ten minutes.
# Allow at most 60 seconds of future clock skew; keep the server clock synchronized.
if ((age > 600) or (age < -60)):
print("Delivery timestamp is outside the accepted window.")
sys.exit()
signedBytes = chilkat2.BinData()
success = signedBytes.AppendBd(rawBody)
if (success != True):
print(signedBytes.LastErrorText)
sys.exit()
success = signedBytes.AppendString(timestamp,"utf-8")
if (success != True):
print(signedBytes.LastErrorText)
sys.exit()
mac = chilkat2.Crypt2()
mac.MacAlgorithm = "hmac"
mac.HashAlgorithm = "sha256"
mac.EncodingMode = "base64"
success = mac.SetMacKeyString(primaryKey)
if (success != True):
print(mac.LastErrorText)
sys.exit()
expectedPrimary = mac.MacBdENC(signedBytes)
if (mac.LastMethodSuccess != True):
print(mac.LastErrorText)
sys.exit()
success = mac.SetMacKeyString(secondaryKey)
if (success != True):
print(mac.LastErrorText)
sys.exit()
expectedSecondary = mac.MacBdENC(signedBytes)
if (mac.LastMethodSuccess != True):
print(mac.LastErrorText)
sys.exit()
# Blind both sides with a fresh secret random key before equality comparison.
# Never compare the original HMAC strings using a prefix-short-circuit comparison.
# A host-language receiver can instead use its standard constant-time byte comparison.
random = chilkat2.Prng()
comparisonKey = random.GenRandom(32,"base64")
if (random.LastMethodSuccess != True):
print(random.LastErrorText)
sys.exit()
success = mac.SetMacKeyEncoded(comparisonKey,"base64")
if (success != True):
print(mac.LastErrorText)
sys.exit()
pExpected = mac.MacStringENC(expectedPrimary)
if (mac.LastMethodSuccess != True):
print(mac.LastErrorText)
sys.exit()
pReceived = mac.MacStringENC(primarySignature)
if (mac.LastMethodSuccess != True):
print(mac.LastErrorText)
sys.exit()
sExpected = mac.MacStringENC(expectedSecondary)
if (mac.LastMethodSuccess != True):
print(mac.LastErrorText)
sys.exit()
sReceived = mac.MacStringENC(secondarySignature)
if (mac.LastMethodSuccess != True):
print(mac.LastErrorText)
sys.exit()
validPrimary = (primaryKey != "") and (primarySignature != "") and (pExpected == pReceived)
validSecondary = (secondaryKey != "") and (secondarySignature != "") and (sExpected == sReceived)
if ((validPrimary == False) and (validSecondary == False)):
print("Signature verification failed.")
sys.exit()
# Parse JSON only after signature verification.
webhookEvent = chilkat2.JsonObject()
success = webhookEvent.Load(rawBody.GetString("utf-8"))
if (success != True):
print(webhookEvent.LastErrorText)
sys.exit()
print("Verified event ID: " + webhookEvent.StringOf("id"))
print("Trigger: " + webhookEvent.StringOf("trigger"))
# Deduplicate using event.id, not BOX-DELIVERY-ID, which changes on retries.
# Verify the target belongs to your configured webhook before dispatching work.