LinkedIn Webhook推送事件签名验证失败求助
LinkedIn Webhook推送事件签名验证失败求助
我刚配置了一个Webhook,用来接收LinkedIn的社交事件,但在请求验证这一步卡壳了,不管怎么试,验证结果都是false,快把我搞疯了😭。我是照着官方文档来操作的,但就是过不了验证。
下面是我的Webhook接口代码:
async def process_event(self, request: Request, x_li_signature: str = Header(None)): """ Endpoint to handle LinkedIn webhook events. """ 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
有没有大佬能给我指条明路?我试了好多种写法都没成功,提前感谢各位了!
备注:内容来源于stack exchange,提问作者Seamus O Connor




