REST请求中基于python证书的认证

2024-09-25 00:35:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用python语言将REST请求与基于证书的身份验证一起发送到提供restapi的给定服务器,但是经过数小时的搜索和尝试,我认为我需要帮助。在

我有一个来自上述服务器的签名证书和证书的密钥。 服务器本身也提供https证书。在

我试过图书馆httplib.HTTPSConnection公司名称:


    import httplib
    import urllib

    clientCert = "client.crt"
    clientKey = "client.key"
    serverCert = 'server.crt'
    serverApi = "/api/getExample"
    serverHost = "restapi.example.com"
    serverPort = 443
    requestMethod = "POST"
    params = urllib.urlencode({'someId': 'myId'})
    headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "application/json"}

    conn = httplib.HTTPSConnection(serverHost, serverPort, key_file=clientKey, cert_file=clientCert)
    conn.request(requestMethod, serverApi, params, headers)
    response = conn.getresponse()
    conn.getresponse()
    conn.close()

我得到ssl.SSLError: SSL: CERTIFICATE_VERIFY_FAILED
有没有可能让基于证书的身份验证与该库一起运行?在


Tags: keyimport服务器client身份验证restapiurllibconn
1条回答
网友
1楼 · 发布于 2024-09-25 00:35:23

我能够在“请求”库的帮助下运行它。在


    import json
    import requests

    clientCrt = "cc.crt"
    clientKey = "ck.key"
    url = "https://example.com/api"
    payload = { "someId": "myID" }
    certServer = 'cs.crt'
    headers = {'content-type': 'application/json'}
    r = requests.post(url, data=json.dumps(payload), verify=certServer, headers=headers, cert=(clientCrt, clientKey))
    print(r.status_code)
    print(r.json())

就这么简单

相关问题 更多 >