无法使用 Python 请求执行 API 登录并发布 api 调用 [英] Unable to perform API login using Python Request and post api calls

查看:52
本文介绍了无法使用 Python 请求执行 API 登录并发布 api 调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 python-requests 执行登录身份验证.

I'm trying to perform a login authentication using python-requests.

我正在尝试使用 AJAX 身份验证访问网站的 API 调用.因此,我使用用户名和密码登录网站,并且是 login_url(AJAX API URL).然后尝试将登录响应的 cookie 用于我的下一个 API 请求.正如您在接下来的代码中看到的,我使用登录响应的 cookie 作为下一个 API 调用的标头.

I'm trying to access an API call of a website with AJAX Authentication. Hence I log in to the website using username and password and the is login_url(AJAX API URL). Then trying to use the cookies of login response for my next API request. As you have seen in the code in the next I'm using the cookie of login response as the header for the next API call.

我希望有人能帮助我找出我请求中的问题.

I hope someone could help me to identify the issue in my request.

作为参考,我的代码是

from requests import Session
import requests
class Login:
  
    def sendRequestWithAuthentication(self,loginDetails,requestDetails):
        user_agent = {'User-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36'}
        action_url=loginDetails['action_url'] if 'action_url' in loginDetails.keys() else None
        pay_load=loginDetails['login_details'] if 'login_details' in loginDetails.keys() else None
        session_requests = requests.session()
        if action_url and pay_load:         
            act_resp=session_requests.post(action_url, data=pay_load, headers=user_agent)
            auth_cookies=act_resp.cookies.get_dict()
            url,method,request_payload = requestDetails['url'],requestDetails['method'],requestDetails['payload']
            querystring=requestDetails['querystring']
            headers={**user_agent,**requestDetails['headers']}
            if method == 'GET' or method == 'get':
               response=session_requests.get(url,headers=headers,cookies=auth_cookies,data=request_payload,params=querystring)
            elif method == 'POST' or method == 'post':
               response=session_requests.get(url,headers=headers,cookies=auth_cookies,data=request_payload,params=querystring)
        return response.json()       

为此,我收到以下错误

Traceback (most recent call last):
 File "C:\Users\david\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Python 3.8\RequestsVenv\lib\site-packages\urllib3\connectionpool.py", line 670, in urlopen
  httplib_response = self._make_request(
 File "C:\Users\david\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Python 3.8\RequestsVenv\lib\site-packages\urllib3\connectionpool.py", line 381, in _make_request
  self._validate_conn(conn)
 File "C:\Users\david\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Python 3.8\RequestsVenv\lib\site-packages\urllib3\connectionpool.py", line 976, in _validate_conn
  conn.connect()
 File "C:\Users\david\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Python 3.8\RequestsVenv\lib\site-packages\urllib3\connection.py", line 361, in connect
  self.sock = ssl_wrap_socket(
 File "C:\Users\david\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Python 3.8\RequestsVenv\lib\site-packages\urllib3\util\ssl_.py", line 377, in ssl_wrap_socket
  return context.wrap_socket(sock, server_hostname=server_hostname)
 File "C:\Users\david\AppData\Local\Programs\Python\Python38-32\lib\ssl.py", line 500, in wrap_socket
  return self.sslsocket_class._create(
 File "C:\Users\david\AppData\Local\Programs\Python\Python38-32\lib\ssl.py", line 1040, in _create
  self.do_handshake()
 File "C:\Users\david\AppData\Local\Programs\Python\Python38-32\lib\ssl.py", line 1309, in do_handshake
  self._sslobj.do_handshake()
 ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1108)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
 File "C:\Users\david\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Python 3.8\RequestsVenv\lib\site-packages\requests\adapters.py", line 439, in send
  resp = conn.urlopen(
 File "C:\Users\david\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Python 3.8\RequestsVenv\lib\site-packages\urllib3\connectionpool.py", line 724, in urlopen
  retries = retries.increment(
 File "C:\Users\david\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Python 3.8\RequestsVenv\lib\site-packages\urllib3\util\retry.py", line 439, in increment
  raise MaxRetryError(_pool, url, error or ResponseError(cause))
 urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='sso1.nbnco.net.au', port=443): Max retries exceeded with url: /F5Networks-SSO-Req?SSO_ORIG_URI=aHR0cHM6Ly9pcGFjdC5uYm5jby5uZXQuYXUvaXBhY3QvaW5kZXgvZG9sZKKExvZ2lu (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1108)')))
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
 File "ValidateAPI.py", line 181, in <module>
  z=ValidateAPI()
 File "ValidateAPI.py", line 17, in __init__
  self.getActivity(sys.argv[1].upper())
 File "ValidateAPI.py", line 37, in getActivity
  self.getTestCase(main_test,sub_test)
 File "ValidateAPI.py", line 62, in getTestCase
  data=self.sendRequestWithAuthentication(t_case['login_credentials'],api_param)
 File "C:\ACCELARATE\API\API_LATEST\API\Login.py", line 18, in sendRequestWithAuthentication
  act_resp=session_requests.post(action_url, data=pay_load, headers=user_agent)
 File "C:\Users\david\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Python 3.8\RequestsVenv\lib\site-packages\requests\sessions.py", line 578, in post
  return self.request('POST', url, data=data, json=json, **kwargs)
 File "C:\Users\david\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Python 3.8\RequestsVenv\lib\site-packages\requests\sessions.py", line 530, in request
  resp = self.send(prep, **send_kwargs)
 File "C:\Users\david\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Python 3.8\RequestsVenv\lib\site-packages\requests\sessions.py", line 665, in send
  history = [resp for resp in gen] if allow_redirects else []
 File "C:\Users\david\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Python 3.8\RequestsVenv\lib\site-packages\requests\sessions.py", line 665, in <listcomp>
  history = [resp for resp in gen] if allow_redirects else []
 File "C:\Users\david\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Python 3.8\RequestsVenv\lib\site-packages\requests\sessions.py", line 237, in resolve_redirects
  resp = self.send(
 File "C:\Users\david\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Python 3.8\RequestsVenv\lib\site-packages\requests\sessions.py", line 643, in send
  r = adapter.send(request, **kwargs)
 File "C:\Users\david\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Python 3.8\RequestsVenv\lib\site-packages\requests\adapters.py", line 514, in send
  raise SSLError(e, request=request)
 requests.exceptions.SSLError: HTTPSConnectionPool(host='sso1.organization.net.us', port=443): Max retries exceeded with url: /F5Networks-SSO-Req?SSO_ORIG_URI=aHR0cHM6Ly9pcGFjdC5uYm5jby5uZXQuYXHUvaXBhY3QvaW5kZXgvZG9sZExvZ2lu (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1108)')))       

更新

网站登录是通过多重身份验证完成的

UPDATE

The website login is done through multi factor authentication

推荐答案

我认为您应该解决的第一个问题是请求不信任该站点的证书,就像最后一个错误行指出的那样.也许尝试先添加证书.检查此处以了解如何设置证书.对不起,我的回答很简短.我会写评论,但我还是新人,因此不允许发表评论.

I think the first issue that you should address is that requests won't trust the cert of that site, like the last error line states. Maybe try to add the cert first. Check here for how to set the cert. Sorry for the short answer. I would've written a comment, but I'm still new and am therefore not allowed to comment.

这篇关于无法使用 Python 请求执行 API 登录并发布 api 调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆