【发布时间】:2022-03-15 12:00:26
【问题描述】:
我编写了一个接口来使用 python 向内部可听 api 发出请求。每个 API 请求都需要使用 RSA SHA256 进行签名。
现在我想用 Postman 测试 API 的端点并使用预请求脚本功能。但我对javascript并不坚定。也许有人可以帮助我将以下 python 函数转换为 Postman 脚本:
def sign_request(
request: httpx.Request, adp_token: str, private_key: str
) -> httpx.Request:
"""
Helper function who creates a signed requests for authentication.
:param request: The request to be signed
:param adp_token: the token is obtained after register as device
:param private_key: the rsa key obtained after register as device
:returns: The signed request
"""
method = request.method
path = request.url.path
query = request.url.query
body = request.content.decode("utf-8")
date = datetime.utcnow().isoformat("T") + "Z"
if query:
path += f"?{query}"
data = f"{method}\n{path}\n{date}\n{body}\n{adp_token}"
key = rsa.PrivateKey.load_pkcs1(private_key.encode())
cipher = rsa.pkcs1.sign(data.encode(), key, "SHA-256")
signed_encoded = base64.b64encode(cipher)
signed_header = {
"x-adp-token": adp_token,
"x-adp-alg": "SHA256withRSA:1.0",
"x-adp-signature": f"{signed_encoded.decode()}:{date}"
}
request.headers.update(signed_header)
return request
我发现了如何获取请求方法和正文。我可以通过pm.request.url.getPathWithQuery() 获取路径和查询。要将标头添加到请求中,我使用pm.request.headers.add。
但我不知道如何获取 isoformat 中的日期时间、连接字符串和签署数据。
【问题讨论】:
-
这应该对你有帮助 - blog.kiprosh.com/…
标签: javascript python postman sign