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.?
Related
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)
I'm tying to get the data from the Cloudhub API which resides on Mulesoft.
I tried to access through postman (With the same Client Credentials - Bearer Authorization) and it's working fine (I can able to get the result with proper get requests).
But when I tried to do the same with Python requests library I ran into issues. Here is my piece of code:
import requests
import json, os
CLIENT_ID = os.environ['CLIENT_ID']
CLIENT_SECRET = os.environ['CLIENT_SECRET']
grant_type = 'client_credentials'
body_params = {'grant_type' : grant_type}
headers = {'Accept': '*/*',
'Cache-Control':'no-cache',
'Accept-Encoding': 'gzip, deflate',
'Content-Type':'application/json, application/x-www-form-urlencoded',
'Connection': 'keep-alive'}
url='https://<domain-name>-api.us-w2.cloudhub.io/api/token'
response = requests.post(url, data=body_params, auth = (CLIENT_ID, CLIENT_SECRET), headers= headers)
token_raw = json.loads(response.text)
print(token_raw)
Result: {'error': 'Authentication denied.'}
All I need to know is
How it's working fine with Postman but why I'm not able to connect with python code?
Is there anything I've to change in my code or any additional information needed for this request? or am I passing the correct endpoint in receiving the access token for Cloudhub API?
Please post your suggestions or any documentation that I need to refer.
Hope the information that I gave is clear and Thanks in Advance !!
I found the answer of my own question. I can get it from the postman itself.
Here is my code for API Call with Python.
import http.client
import os
conn = http.client.HTTPSConnection("<domain-name>-api.us-w2.cloudhub.io")
payload = ''
headers = {
'client_id': os.environ['CLIENT_ID'],
'client_secret': os.environ['CLIENT_SECRET']
}
conn.request("GET", "/api/<Query that you want to pass - endpoint>", payload, headers)
response = conn.getresponse()
resp_data = response.read()
print(resp_data.decode("utf-8"))
The URL is incorrect. To call CloudHub REST API you need to obtain a bearer token from Anypoint Platform REST API. The URL mentioned looks to for some application deployed in CloudHub, not from the platform APIs. This is the same method than to get the bearer token to use in Anypoint MQ Admin API. It looks like you are trying to use the Anypoint MQ Broker API, which is an Anypoint MQ specific token.
Example in Curl to get an Anypoint Platform token:
$ curl -H "Content-Type: application/json" -X POST -d '{"username":"joe.blogs","password":"sample.password"}' https://anypoint.mulesoft.com/accounts/login
{
"access_token": "f648eea2-3704-4560-bb46-bfff79712652",
"token_type": "bearer",
"redirectUrl": "/home/"
}
Additionally the Content-type of your example seems incorrect because it has 2 values.
I'm sure the Postman request is different for it to work, or maybe it works only for the Anypoint MQ Broker API.
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.
I'm working with an external API that unfortunately doesn't have that great error logging.
I use django 1.9.5 and requests 2.11.1.
When I make the following request with the built-in python server (python manage.py runserver) on my local machine, I get back a 200 status code, so this works fine.
r = requests.post(
'https://plazaapi.bol.com/offers/v1/%s' % product.ean, data=xml_to_send,
headers=headers)
headers are a dictionary of the date, an authorization code and the content-type
.
But as there is a problem with requests on GAE according to other answers on this site, I have tried to use the requests_toolbelt monkeypatch and urlfetch, but I always get back the following error then:
Request contains invalid authentication headers
Code with the monkeypatch:
import requests_toolbelt.adapters.appengine
requests_toolbelt.adapters.appengine.monkeypatch()
r = requests.post(
'https://plazaapi.bol.com/offers/v1/%s' % product.ean, data=xml_to_send,
headers=headers)
and
from google.appengine.api import urlfetch
r = urlfetch.fetch(
url='https://plazaapi.bol.com/offers/v1/%s' % product.ean,
payload=xml_to_send,
method=urlfetch.POST,
headers=headers,
follow_redirects=False) # tried this, but has no effect.
The headers I'm setting are:
headers = {'Content-Type': 'application/xml',
'X-BOL-Date': date,
'X-BOL-Authorization': signature}
Is GAE changing my request and adding headers? If so, can I stop it
from doing so?
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'})