如何验证Keycloak webhook请求?



我正在实现一个端点,使用webhook从Keycloak接收事件,但我不知道如何验证这个请求。

我看到请求包含一个标头"X-Keycloak-Signature"另外,我设置了一个WEBHOOK_SECRET。似乎我需要从请求和秘密中生成这个签名,然后比较它们。它看起来像这样:

import os
import hashlib
from flask import abort, request

def validate_keycloak_signature(f):
def wrapper(self, *args, **kwargs):
secret = os.getenv("WEBHOOK_SECRET")
method = request.method
uri = request.url
body = request.get_data(as_text=True)
smub = secret + method + uri + body
h = hashlib.sha256(smub.encode("utf-8")).hexdigest()
signature = request.headers.get("X-Keycloak-Signature")
if h != signature:
return abort(403)
return f(self, *args, **kwargs)

return wrapper

但是,我不知道算法。这里,我试了这个:

1. Create a string that concatenates together the following: Client secret + http method + URI + request body (if present)
2. Create a SHA-256 hash of the resulting string.
3. Compare the hash value to the signature. If they're equal then this request has passed validation.

但是它不起作用。有人有什么想法吗?

我意识到这个签名不是由Keycloak本身生成的,而是由Phasetwo为我提供了一个webhook插件。

所以我只是查看了它的代码并找到了算法。

这就是如何生成签名来验证它:

def validate_keycloak_signature(f):
...
secret = os.getenv("WEBHOOK_SECRET")
body = request.data
control_signature = hmac.new(
key=bytes(secret, "utf-8"),
msg=body,
digestmod=hashlib.sha256
).hexdigest()
...

最新更新