【问题标题】:Python requests with certificates带有证书的 Python 请求
【发布时间】:2021-02-10 08:40:48
【问题描述】:

我正在尝试让汇丰银行开放银行的沙盒工作。仅当我使用 -k 禁用验证时,来自他们的 documentation 的 curl 命令才会给我一个访问令牌。请注意,我从我的汇丰开发人员dashboard 下载了xyz.derserver.key

curl -v -k -X POST \
--cert hsbc/qwac_PSP_PI,PSP_AS,PSP_IC,PSP_AI_27_10_2020.der \
--cert-type DER \
--key hsbc/server.key \
-H "Content-Type: application/x-www-form-urlencoded" \
-H "Accept: application/json" \
-H "x-fapi-financial-id: test" \
-H "Cache-Control: no-cache" \
-d 'grant_type=client_credentials&scope=accounts&client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer&client_assertion=xyz' \
"https://sandbox.hsbc.com/psd2/obie/v3.1/as/token.oauth2"

由于这是有效的,我正在尝试对 requests 做同样的事情,但在如何使用证书方面遇到了困难。我知道requests 支持cert 关键字,但似乎我还需要添加其他参数。有没有办法可以指定证书类型和相应的密钥?

import requests

headers = {
    "Content-Type": "application/x-www-form-urlencoded",
    "Accept": "application/json",
    "x-fapi-financial-id": "test",
    "Cache-Control": "no-cache",
}
params = {
    "grant_type": "client_credentials",
    "scope": "accounts",
    "client_assertion_type": "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
    "client_assertion": "xyz",
}
url = "https://sandbox.hsbc.com/psd2/obie/v3.1/as/token.oauth2"

requests.post(url=url,
              headers=headers,
              params=params,
              cert="hsbc/qwac_PSP_PI,PSP_AS,PSP_IC,PSP_AI_27_10_2020.der",
              verify=False).json()

【问题讨论】:

  • 您那里似乎有一些私人数据('client_assertion')。请删除它并用其他东西替换它
  • 抱歉,我认为没有必要,因为它是一个沙盒。我现在已经删除了。
  • 使用 openssl 将您的证书和密钥转换为 PEM 格式并提供 cert= 作为元组 (cert, key) 或将两者放在一个文件中。
  • @KlausD。确实很好用。谢谢! requests 是否总是期望 .pem 格式?

标签: python ssl python-requests certificate


【解决方案1】:

感谢@KlausD。这在使用openssl.der 转换为.pem 后现在可以工作了:

openssl x509 -inform der -in qwac_xyz.der -out qwac_xyz.pem
import requests

headers = {
    "Content-Type": "application/x-www-form-urlencoded",
    "Accept": "application/json",
    "x-fapi-financial-id": "test",
    "Cache-Control": "no-cache",
}
params = {
    "grant_type": "client_credentials",
    "scope": "accounts",
    "client_assertion_type": "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
    "client_assertion": "xyz",
}
url = "https://sandbox.hsbc.com/psd2/obie/v3.1/as/token.oauth2"

requests.post(url=url,
              headers=headers,
              params=params,
              cert=("hsbc/qwac_xyz.pem", "hsbc/server.key"),
              verify=False).json()

【讨论】:

    猜你喜欢
    • 2022-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-18
    • 2023-04-04
    • 2016-04-18
    相关资源
    最近更新 更多