Однако, что бы я ни пытался, я продолжаю получать ложные сведения о проверке, что заставляет меня добиваться успеха.
Вот моя конечная точка:
Код: Выделить всё
async def process_event(self, request: Request, x_li_signature: str = Header(None)):
"""
Endpoint to handle LinkedIn webhook events.
"""
# signature = request.headers.get("X-LINKEDIN-SIGNATURE")
signature = x_li_signature
raw_body = await request.body()
print(f"raw_body: {raw_body}")
payload = raw_body.decode("utf-8")
print(payload)
print(f"Comparing signature: {signature}")
event = json.loads(payload)
print(f"Webhook Event Received: {event}")
verified = self.verify_signature(payload=event, signature=signature, secret=CLIENT_SECRET)
if verified is False:
print("Signature not verified")
raise HTTPException(status_code=403, detail="Invalid signature")
Код: Выделить всё
def verify_signature(self, payload: dict, signature: str, secret: str) -> bool:
"""
Verify the integrity of the LinkedIn push event.
Args:
payload (bytes): The raw request body.
signature (str): The X-LI-SIGNATURE header value.
secret (str): The LinkedIn app's client secret.
Returns:
bool: True if the signature is valid, False otherwise.
"""
payload = json.dumps(payload)
# Compute the HMAC-SHA256 signature
# Prefix "hmacsha256=" to the payload to form the encryption string
encryption_string = f"hmacsha256={payload}"
print(f"Comparing payload: {encryption_string} with signature: {signature}")
# Compute the HMAC-SHA256 signature
try:
computed_signature = hmac.new(
key=secret.encode("utf-8"),
msg=encryption_string,
digestmod=hashlib.sha256
).digest()
print(f"computed_signature: {computed_signature}")
# Encode the computed signature in Base64
encoded_signature = base64.b64encode(computed_signature).decode("utf-8")
print(f"encoded_signature: {encoded_signature}")
# Use compare_digest for secure comparison
verified = hmac.compare_digest(encoded_signature, signature)
print(f"verified: {verified}")
return verified
except Exception as e:
print("Could not verify signature")
print(e)
return False
Подробнее здесь: https://stackoverflow.com/questions/793 ... push-event
Мобильная версия