Unable to perform API login using Python Request and post api calls

帅比萌擦擦* 提交于 2020-06-28 03:57:16

问题


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

Explaination

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.

For reference my code is

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

For this, I'm getting the following error

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


回答1:


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.



来源:https://stackoverflow.com/questions/62044412/unable-to-perform-api-login-using-python-request-and-post-api-calls

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!