REST请求中基于python证书的身份验证

时间:2018-08-17 08:37:07

标签: python rest authentication certificate

我尝试通过python将具有基于证书的身份验证的REST请求发送到提供REST api的给定服务器,但是经过数小时的搜索和尝试,我认为我需要帮助。

我有来自提到的服务器的签名证书以及该证书的密钥。 服务器本身也提供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
可以在该库中运行基于证书的身份验证吗?

1 个答案:

答案 0 :(得分:1)

借助“请求”库,我得以使其运行。


    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())

就这么简单