Python requests get: "Dynamic backend host not specified" - python

I am trying to do a very simple https "get" method using python's requests package, and it seems to work, except that I get an error message from the host machine saying:
"Dynamic backend host not specified"
I don't know exactly what that means. Is there some parameter that needs to be set in the get method?

Okay, it turns out that it's a matter of setting up the headers correctly.
Adding
headers = {'content-type': 'application/json', 'accept':'application/json'}
fixed the problem.
The code for the working call:
r = requests.post(
HELLO_WORLD_URL,
cert = (os.path.join(CERT_DIR, "cert.pem"), os.path.join(CERT_DIR, "example-key.pem")),
auth = (USER_ID, PASSWORD),
headers = {'content-type': 'application/json', 'accept':'application/json'})

Related

Python API request to internal API with OKTA Authentication

I used to selenium for downloading special reports from webpage where I have to login. Webpage has integrated OKTA Authentication plugin . I find out that there would be better and more effective use internal API requests. So I tried find how to use request python library with creating session, but I am unsuccessful. I tried this code, but it ends with 400 error.
payload = {"password":"password","username":"username","options":{"warnBeforePasswordExpired": True,"multiOptionalFactorEnroll": True}}
with requests.Session() as s:
p = s.post('https://sso.johndeere.com/api/v1/authn', data=payload)
r = s.get("requested_url")
print(p)
I am unable get throw auth. Has anybody experience with breaking OKTA auth plugin using requests library?
Thanks
Best Regards
Merry Christmas and Welcome to Stackoverflow!
Firstly, an HTTP error code of 400 error means one or more settings is wrong at the client side. You can learn more about it here.
You seem to be missing out important headers configuration. You need to set the content-type header correctly otherwise the destination server won't be able to process your data.
Also, as a bonus point. You need to format your payload into a valid JSON string before sending out the request too.
import requests
import json
# Setup proper headers
headers = {
"accept": "application/json, text/plain, */*",
"content-type": "application/json; charset=UTF-8"
}
# Your body data here
payload = {"password":"password","username":"username","options":{"warnBeforePasswordExpired": True,"multiOptionalFactorEnroll": True}}
payload_json = json.dumps(payload) # Format it into a valid JSON str
with requests.Session() as s:
p = s.post('https://sso.johndeere.com/api/v1/authn', headers=headers, data=payload_json)
r = s.get("requested_url")
print(p.content)

How to send post to laravel api from python?

This is my python request code.
url = "https://test.com/"
r = requests.get(url, verify=False)
xsrf_token = r.cookies.get("XSRF-TOKEN")
headers = {
'X-XSRF-TOKEN':xsrf_token
}
data = {"account": "O_O#gmail.com", "password": "123123"}
r = requests.post(url+'/app/get/users', verify=False, data = data, headers=headers)
In laravel log, I got
[2019-12-27 16:09:14] local.ERROR: The payload is invalid. {"exception":"[object] (Illuminate\Contracts\Encryption\DecryptException(code: 0): The payload is invalid. at /var/www/html/test/vendor/laravel/framework/src/Illuminate/Encryption/Encrypter.php:195)
[stacktrace]
Have any method to solve that? Thanks.
You can't solve the issue with a static xsrf alone since it's doing its job preventing Cross Site Request Forging wich is exactly what you're doing in that piece of code.
To use a route as an API, the laravel installation needs to be configured that way, so, if needed, a stateless way of authentification is used (jwt for example) instead of the session with xsrf token for post methods.
Basicly if it's not configured to be used as an API, you will not be able to use it as an API.

authentication using httplib in python

I am using python 2.7.10. How can I login using httplib connection method.
import httplib
conn = httplib.HTTPConnection("192.18.33.10")
conn.request("POST", "/user/user.form?name=Maharjun&age=23")
res = conn.getresponse()
data = res.read()
What this user.form does is, it will accept some details like name and age from users and server will save them in database. This details can only filled by authenticated users.
I tried some suggestions from python http.requests but those are not working in python-2.7.10.
I know about postman. So, I sent same request in postman using basic authentication method and i converted that into python scripts. In postman we can convert postman-URL into curl/shell/python scripts. So, I converted them into python scripts.
Both are same requests. But I am able to submit the data using postman. But not able to do with python.
postman is giving me a post-man token and basic authentication in headers like below code. is there any mistakes in the code or any suggestions?
import httplib
conn = httplib.HTTPConnection("192.18.33.10")
url = "/user/user.form?name=Maharjun&age=23"
headers = {
'authorization': "Basic some-token",
'cache-control': "no-cache",
'postman-token': "some-token"
}
response = conn.request("POST", url, headers=headers)
print(response.text)
Though it have 'authorization' token I was not able to login by using above code.
can someone help me to write basic authentication using python requests.?

How to connect to REST web service with PUT HTTP method in python using proxy?

I have 'corporate internal tool' where python 2.5.2 is embedded. This mean that I cant use any other version or programming language.
So, code is following for HTTPLIB:
connection = httplib.HTTPSConnection('IP:PORT')
body_content = '<INPUT><Var1>DATA</Var1></INPUT>/r/n'
headers = {Authorization':'Basic XXXXXXXXXXXX','Accept':'text/xml','Content-Length':'XX','Host':'host name','Accept-Encoding':'gzip,deflate'}
connection.request('PUT', '/path/method',body_content, headers)
result = connection.getresponse()
For urllib2 code is following:
body_content = '<INPUT><Var1>DATA</Var1></INPUT>\r\n'
opener = urllib2.build_opener(urllib2.HTTPSHandler)
request = urllib2.Request('https://IP:PORT/path/method', data=body_content)
request.headers={'Content-length': 'XX', 'Host': 'host', 'Accept': 'text/xml', 'Authorization': 'Basic XXXXXXXXXXXXX', 'Accept-encoding': 'gzip,deflate'}
request.get_method = lambda: 'PUT'
url = opener.open(request)
Both of them are working fine in default python 2.5.2 installation.
If I try to use the same code in tool that I got, the following errors appear:
HTTPLIB:
'module' object has no attribute 'ssl'
URLLIB2:
urlopen error unknown url type: https
As I understood, SSL support is removed. By the way: I can write my own libraries and placing them to correct folders makes them work.
So, the question is:
How using Proxy connect to web service?
I found following example:
http://www.pha.com.au/kb/index.php/Python_-_Using_a_proxy_for_HTTP_requests
But it is not working in my case. Do you have some suggestion how this can be solved?
It looks that building a separate proxy module for performing the HTTPS query in python can solve this problem. So, what can be the connecting procedure in this case?

Google Data API authentication

I am trying to get my Django app (NOT using Google app engine) retrieve data from Google Contacts using Google Contacts Data API. Going through authentication documentation as well as Data API Python client docs
First step (AuthSubRequest) which is getting the single-use token works fine. The next step(AuthSubSessionToken), which is upgrade single-use token to a session token. The python API call UpgradeToSessionToken() simply didn't work for me it gave me NonAuthSubToken exception:
gd_client = gdata.contacts.service.ContactsService()
gd_client.auth_token = authsub_token
gd_client.UpgradeToSessionToken()
As an alternative I want to get it working by "manually" constructing the HTTP request:
url = 'https://www.google.com/accounts/AuthSubSessionToken'
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'AuthSub token=' + authsub_token,
'User-Agent': 'Python/2.6.1',
'Host': 'https://www.google.com',
'Accept': 'text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2',
'Connection': 'keep-alive',
}
req = urllib2.Request(url, None, headers)
response = urllib2.urlopen(req)
this gives me a different error:
HTTP Error 302: The HTTP server returned a redirect error that would lead to an infinite loop. The last 30x error message was: Moved Temporarily
What am I doing wrong here? I'd appreciate help/advice/suggestions with either of the methods I am trying to use: Python API call (UpgradeToSessionToken) or manually constructing HTTP request with urllib2.
According to the 2.0 documentation here there is a python example set...
Running the sample code
A full working sample client, containing all the sample code shown in this document, is available in the Python client library distribution, under the directory samples/contacts/contacts_example.py.
The sample client performs several operations on contacts to demonstrate the use of the Contacts Data API.
Hopefully it will point you in the right direction.
I had a similar issue recently. Mine got fixed by setting "secure" to "true".
next = 'http://www.coolcalendarsite.com/welcome.pyc'
scope = 'http://www.google.com/calendar/feeds/'
secure = True
session = True
calendar_service = gdata.calendar.service.CalendarService()
There are four different ways to authenticate. Is it really that important for you to use AuthSub? If you can't get AuthSub to work, then consider the ClientLogin approach. I had no trouble getting that to work.

Categories

Resources