问题描述
我收到了带有用户名和密码的证书.p12.
在我的系统中安装此证书后,我可以使用 Rest Client 进行发布请求.
我如何使用此证书通过 Python 请求方法对 Rest API 上的 post 请求进行身份验证?
我正在使用下面的代码,但它不起作用.
导入请求标头 = {'内容类型':'应用程序/json'}有效载荷 = {'文件夹':'/Trial/trial_dir'}response = requests.post('https://<IP>:8080/siteapi/availabletests', params=payload, headers=headers, verify='C:\\Users\\ukhare\\Desktop\\sigos\\cert.p12', auth=('trial_test','trialtest'))
并得到以下错误:
回溯(最近一次调用最后一次):文件D:\m\Python34\lib\site-packages\urllib3\connection.py",第 171 行,在 _new_conn(self._dns_host, self.port), self.timeout, **extra_kw)文件D:\m\Python34\lib\site-packages\urllib3\util\connection.py",第 79 行,在 create_connection 中提高错误文件D:\m\Python34\lib\site-packages\urllib3\util\connection.py",第 69 行,在 create_connection 中sock.connect(sa)ConnectionRefusedError: [WinError 10061] 由于目标机器主动拒绝,无法建立连接在处理上述异常的过程中,又发生了一个异常:回溯(最近一次调用最后一次):文件D:\m\Python34\lib\site-packages\urllib3\connectionpool.py",第 600 行,在 urlopen分块=分块)_make_request 中的文件D:\m\Python34\lib\site-packages\urllib3\connectionpool.py",第 343 行self._validate_conn(conn)文件D:\m\Python34\lib\site-packages\urllib3\connectionpool.py",第 849 行,在 _validate_conn连接.connect()文件D:\m\Python34\lib\site-packages\urllib3\connection.py",第 314 行,在连接中conn = self._new_conn()文件D:\m\Python34\lib\site-packages\urllib3\connection.py",第 180 行,在 _new_connself, "无法建立新连接:%s" % e)urllib3.exceptions.NewConnectionError: <urllib3.connection.VerifiedHTTPSConnection object at 0x036B0230>: 建立新连接失败:[WinError 10061] 由于目标机器主动拒绝,无法建立连接在处理上述异常的过程中,又发生了一个异常:回溯(最近一次调用最后一次):文件D:\m\Python34\lib\site-packages\requests\adapters.py",第 445 行,发送超时=超时文件D:\m\Python34\lib\site-packages\urllib3\connectionpool.py",第 638 行,在 urlopen_stacktrace=sys.exc_info()[2])文件D:\m\Python34\lib\site-packages\urllib3\util\retry.py",第398行,增量引发 MaxRetryError(_pool, url, error 或 ResponseError(cause))urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='IP', port=8080): Max retries exceeded with url:/siteapi/availabletests?folder=%2FTial%2Ftrial_dir (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object)在 0x036B0230>:无法建立新连接:[WinError 10061] 无法建立连接,因为目标机器主动拒绝它',))在处理上述异常的过程中,又发生了一个异常:回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中文件D:\m\Python34\lib\site-packages\requests\api.py",第 112 行,在帖子中返回请求('post', url, data=data, json=json, **kwargs)文件D:\m\Python34\lib\site-packages\requests\api.py",第 58 行,在请求中返回 session.request(method=method, url=url, **kwargs)文件D:\m\Python34\lib\site-packages\requests\sessions.py",第 512 行,在请求中resp = self.send(prep, **send_kwargs)文件D:\m\Python34\lib\site-packages\requests\sessions.py",第 622 行,发送r = adapter.send(request, **kwargs)文件D:\m\Python34\lib\site-packages\requests\adapters.py",第 513 行,发送引发 ConnectionError(e, request=request)requests.exceptions.ConnectionError: HTTPSConnectionPool(host='IP', port=8080): Max retries exceeded with url:/siteapi/availabletests?folder=%2FTial%2Ftrial_dir (由 NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection 对象引起)在 0x036B0230>:无法建立新连接:[WinError 10061] 无法建立连接,因为目标机器主动拒绝它',))
Ref: https://github.com/m-click/requests_pkcs12
我使用的是有效载荷
data={"folder": "/Trial/trial_dir"}
这是一个字典,而它应该是一个正确的字典字符串
data='{"folder": "/Trial/trial_dir"}'
因此,以下是使用 python 成功发布请求的结果:-
- 标题参数应该是一个字典.
例如
headers={'Content-Type': 'application/json'}
- 数据参数应该是字符串格式的字典.
例如
data='{"folder": "/Trial/trial_dir"}'
- Verify 应设置为 False :
verify=False
以忽略验证 SSL 证书.
以下是我提出的请求的状态和内容:
>>>导入json>>>从 requests_pkcs12 导入获取,发布>>>url = 'https://IP:8080/siteapi/availabletests'>>>pkcs12_filename = 'C:\\Users\\ukhare\\Desktop\\tests\\trial_tata.p12'>>>pkcs12_password = '试用'>>>response = post(url, data='{"folder": "/Trial/trial_dir"}', headers={'Content-Type': 'application/json'}, verify=False, pkcs12_filename=pkcs12_filename,pkcs12_password=pkcs12_password)D:\m\Python34\lib\site-packages\urllib3\connectionpool.py:857: InsecureRequestWarning: 正在发出未经验证的 HTTPS 请求.强烈建议添加证书验证.请参阅:https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings不安全请求警告)>>>打印(响应.status_code)200>>>打印(json.dumps(json.loads(response.content.decode("utf-8")), indent=4, separators=(',', ': '), sort_keys=True)){可用测试":["/Trial/trial_test/HTTP_Download"],服务错误":空I have received a certificate.p12 with username and password.
While I am able to use Rest Client for post requests after i install this certificate in my system.
How can i use this certificate to authenticate post requests on Rest API using Python requests method ?
I am using below code but it is not working.
import requests
headers = {'Content-Type': 'application/json'}
payload = {'folder': '/Trial/trial_dir'}
response = requests.post('https://<IP>:8080/siteapi/availabletests', params=payload, headers=headers, verify='C:\\Users\\ukhare\\Desktop\\sigos\\cert.p12', auth=('trial_test','trialtest'))
And getting below error:
Traceback (most recent call last):
File "D:\m\Python34\lib\site-packages\urllib3\connection.py", line 171, in _new_conn
(self._dns_host, self.port), self.timeout, **extra_kw)
File "D:\m\Python34\lib\site-packages\urllib3\util\connection.py", line 79, in create_connection
raise err
File "D:\m\Python34\lib\site-packages\urllib3\util\connection.py", line 69, in create_connection
sock.connect(sa)
ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "D:\m\Python34\lib\site-packages\urllib3\connectionpool.py", line 600, in urlopen
chunked=chunked)
File "D:\m\Python34\lib\site-packages\urllib3\connectionpool.py", line 343, in _make_request
self._validate_conn(conn)
File "D:\m\Python34\lib\site-packages\urllib3\connectionpool.py", line 849, in _validate_conn
conn.connect()
File "D:\m\Python34\lib\site-packages\urllib3\connection.py", line 314, in connect
conn = self._new_conn()
File "D:\m\Python34\lib\site-packages\urllib3\connection.py", line 180, in _new_conn
self, "Failed to establish a new connection: %s" % e)
urllib3.exceptions.NewConnectionError: <urllib3.connection.VerifiedHTTPSConnection object at 0x036B0230>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "D:\m\Python34\lib\site-packages\requests\adapters.py", line 445, in send
timeout=timeout
File "D:\m\Python34\lib\site-packages\urllib3\connectionpool.py", line 638, in urlopen
_stacktrace=sys.exc_info()[2])
File "D:\m\Python34\lib\site-packages\urllib3\util\retry.py", line 398, in increment
raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='IP', port=8080): Max retries exceeded with url: /siteapi/availabletests?folder=%2FTrial%2Ftrial_dir (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x036B0230>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it',))
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "D:\m\Python34\lib\site-packages\requests\api.py", line 112, in post
return request('post', url, data=data, json=json, **kwargs)
File "D:\m\Python34\lib\site-packages\requests\api.py", line 58, in request
return session.request(method=method, url=url, **kwargs)
File "D:\m\Python34\lib\site-packages\requests\sessions.py", line 512, in request
resp = self.send(prep, **send_kwargs)
File "D:\m\Python34\lib\site-packages\requests\sessions.py", line 622, in send
r = adapter.send(request, **kwargs)
File "D:\m\Python34\lib\site-packages\requests\adapters.py", line 513, in send
raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPSConnectionPool(host='IP', port=8080): Max retries exceeded with url: /siteapi/availabletests?folder=%2FTrial%2Ftrial_dir (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x036B0230>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it',))
Ref: https://github.com/m-click/requests_pkcs12
I was using payload
data={"folder": "/Trial/trial_dir"}
which is a dictionary while it should be a proper string of dictionary
data='{"folder": "/Trial/trial_dir"}'
So the following are the findings for successful post requests with python :-
- Header parameter should be a dictionary.
e.g.
headers={'Content-Type': 'application/json'}
- Data parameter should be a dictionary in string format.
e.g.
data='{"folder": "/Trial/trial_dir"}'
- Verify should be set to False :
verify=False
as to ignore verifying the SSL certificate.
Below is the status and contents received from request I made:
>>> import json
>>> from requests_pkcs12 import get,post
>>> url = 'https://IP:8080/siteapi/availabletests'
>>> pkcs12_filename = 'C:\\Users\\ukhare\\Desktop\\tests\\trial_tata.p12'
>>> pkcs12_password = 'trialtest'
>>> response = post(url, data='{"folder": "/Trial/trial_dir"}', headers={'Content-Type': 'application/json'}, verify=False, pkcs12_filename=pkcs12_filename,pkcs12_password=pkcs12_password)
D:\m\Python34\lib\site-packages\urllib3\connectionpool.py:857: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
InsecureRequestWarning)
>>> print(response.status_code)
200
>>> print(json.dumps(json.loads(response.content.decode("utf-8")), indent=4, separators=(',', ': '), sort_keys=True))
{
"availableTests": [
"/Trial/trial_test/HTTP_Download"
],
"serviceError": null
这篇关于如何使用 .p12 证书对 rest api 进行身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!