maybe someone can help me with this. I'm trying to get a data from a website using Python 2.7, using HTTP Basic Authentication.
The only instructions the website provides is this:
In order for your web service client to authenticate using basic
authentication, the first HTTPS request must include the
"Authorization" header specifying the account credentials to
authenticate with. The header for a such a request would look like
this:
GET /polcs/trade.xml HTTP/1.0
Host: secure.pol.com
Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
I tried few things but neither of them works, for example:
import urllib2
import base64
b = base64.encodestring('USERNAME:PASSWORD').replace('\n', '')
conf = {'headers': {'GET': '/polcs/trade.xml HTTP/1.0', 'Authorization': 'Basic ' + b},
'url': 'secure.pol.com'}
datas = None
request = urllib2.Request(conf['url'], datas, conf['headers'])
result = urllib2.urlopen(request)
This one gives me HTTP Error 403:
url = 'https://secure.pol.com/polcs/data.xml'
request = urllib2.Request(url)
b = base64.encodestring('USERNAME:PASSWORD').replace('\n', '')
request.add_header("Authorization", "Basic " + b)
result = urllib2.urlopen(request)
Can someone please tell me where do I make a mistake trying to get that data?
Thank you!
Related
I am trying to send an API request to a server that needs http authentication.
The (Wordpress server) is set to authenticate the API using basic authentication.
First I am setting the session using the code
with requests.sessions.Session() as session:
session.auth = ('my_user', 'my_password')
session.get(url)
I get 200 as expected.
Then I send the API request
credentials = "user:password"
token = base64.b64encode(credentials.encode())
header = {"Authorization": "Basic " + token.decode('utf-8')}
response = requests.get(url=url, headers=header)
But I get error 401 in the response.
How can I do it differently to make it work?
i have some sample of mine, i hope it'll help you:
header = {....}
data = {...}
response= requests.post(url=url, data=data,headers=header,auth=(user,password))
as far as I know, wordpress does not even accept Authentication user/password by default.
you can only login through cookies (source)
but there is a way to authenticate rest api using user/password and that is plugins. I suggest Wordpress REST API Authentication
then usage would be so easy like :
import requests
headers = {
'Authorization': 'Basic base64encoded <username:password>',
'Content-Type': 'application/x-www-form-urlencoded',
}
data = 'title=sample post&status=publish'
response = requests.post('http://example.com/wp-json/wp/v2/posts', headers=headers, data=data)
Taking from the two answers (thanks!), here is the answer that is a merge of the two.
The API authentication is sent in the header (and an API authentication plugin is needed in WP).
credentials = "user:password"
token = base64.b64encode(credentials.encode())
header = {"Authorization": "Basic " + token.decode('utf-8')}
The session authentication is sent in the auth parameter of the request
response = requests.get(url=url, headers=header, auth=('my_user', 'my_password'))
I am trying to create RFC in cherwell using REST API in Python. I tried first in Swegger UI. I got it working there. I am able to create RFC successfully. Then by following that Curl Request, in python, using request module, I tried and got 401. I found it why i am getting 401. It's because of in Authorization i am using Bearer which is a temporary token. It will live only for 10 minutes. If i do request after 10 minutes i got a 401. Bearer is a compulsory field. I can't make a request without it. I tried to pass username and password instead of Bearer, it didn't work. below is my request,
with open('C:\Cherwell\payload.json') as file:
Data = json.load(file)
payload = Data
header = {"Authorization":"Bearer XXXXXXXX"}
r = requests.post("https:/URL/CherwellAPI/api/V1/savebusinessobject?
api_key=XXXX-XXXX-XXXX-XXXX", auth=('user','pass'), headers = header,
data=json.dumps(payload))
print r
It will be great, if anyone can help who have done this before! Please Advice
Appreciate any help!
Found this solution that I used to address a similar problem. It's a function that requests a token from /CherwellAPI/token and returns a properly formatted Bearer token. You need to pass this Bearer token along in API requests as a Authorization parameter in the API header. Should look like token=bearer_token.
import json
import requests
configFile = 'config.json'
with open(configFile) as cf:
config_data = json.load(cf)
def getCherwellToken():
params = {'apikey' : config_data['cherwell']['client_id']}
data = {'grant_type' : 'password',
'client_id' : config_data['cherwell']['client_id'],
'username' : config_data['cherwell']['username'],
'password' : config_data['cherwell']['password']}
url = 'https://.cherwellondemand.com/CherwellAPI/token'
session = requests.post(url=url, data=data)
if session:
token = json.loads(session.text)
else:
token = None
return 'Bearer ' + token['access_token']
using another call Get Token You can get access token and using that you can request to create a new ticket. This worked for me.
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.?
I tried to connect HP QC using python to create defects and attach files, but I am not able to connect with HP QC. Here is my code:
domain='DEFAULT_773497139'
project='773497139_DEMO'
import requests
url = "https://almalm1250saastrial.saas.hpe.com/qcbin/"
querystring = {"username":"user#gmail.com","password":"password"}
headers = {
'cache-control': "no-cache",
'token': "5d33d0b7-1d04-4989-3349-3005b847ab7f"
}
response = requests.request("POST", url, headers=headers, params=querystring)
#~ print(response.text)
print response.headers
new_header = response.headers
new_url = url+ u'rest/domains/'+domain+u'/projects/'+project
new_querystring = {
"username":"user#gmail.com",
"password":"password",
"domain":'DEFAULT_773497139',
"project":'773497139_DEMO'
}
print new_url
response = requests.request("POST", new_url, headers=new_header, params=new_querystring)
print(response.text)
Now login works fine, but when try other API it asks for, I would get this message:
Authentication failed. Browser based integrations - to login append '?login-form-required=y' to the url you tried to access
If the parameter has been added, then it goes back to login page.
Seems that your urls are not well builded:
base_url ='https://server.saas.hpe.com/qcbin/'
base_url + '/qcbin/rest/domains/
you will get:
..../qcbin/qcbin/...
qcbin twice
The way I do it is to based on python request Sessions. First I create a session, then post my credentials to ../authentication-point/alm-authenticate/ (or sth like this, you should check it) and then using this session I can get, post or do whatever I want.
So:
s = requests.Session()
s.post(`../authentication-point/alm-authenticate/`, data=credentials)
# now session object is authenticated and recognized
# you can s.post, s.get or whatever
I think it's a good url, but I can't check it right now :)
Session issue has beensolved by LWSSO cookie (LWSSO_COOKIE_KEY).
Just send a unicode string to your server and use the header for the basic Authorization as specified by the HP REST API:
login_url = u'https://almalm1250saastrial.saas.hpe.com/qcbin/authentication-point/authenticate'
username,password = user,passwd
logs = base64.b64encode("{0}:{1}".format(username, password))
header['Authorization'] = "Basic {}".format(logs)
POST by using the requests module in python is quite easy:
requests.post(login_url, headers=header)
That's it...now you are authenticated and you can proceed with next action :-) To check on that you can "GET" on:
login_auth = u'https://almalm1250saastrial.saas.hpe.com/qcbin/rest/is-authenticated
you should get a code 200 --> That means you are authenticated.
Hope this help you. Have a nice day and let me know if something is still not clear.
p.s.: to send REST msg in python I am using requests module. It is really easy! You can create a session if you want to send multiple actions--> then work with that sessions--> ALM = requests.session(), then use ALM.post(whatever) and so on :-)
I have some code where I am trying to authenticate against Azure's Resource Manager REST API.
import json
import requests
tenant_id = "TENANT_ID"
app_id = "CLIENT_ID"
password = "APP_SECRET"
token_endpoint = 'http://login.microsoftonline.com/%s/oauth2/token' % tenant_id
management_uri = 'https://management.core.windows.net/'
payload = { 'grant_type': 'client_credentials',
'client_id': app_id,
'client_secret': password
}
auth_response = requests.post(url=token_endpoint, data=payload)
print auth_response.status_code
print auth_response.reason
This returns:
200
OK
However, when I print auth_response.content or auth_reponse.text, I get back a 400 HTML error code and an error message.
HTTP Error Code: 400
Sorry, but we’re having trouble signing you in.
We received a bad request.
I am able to get back the correct information using PostMan, however, with the same URI and payload. I used the "Generate Code" option in Postman to export my request to a Python requests script and tried running that. But, I get the same errors.
Anybody have any idea why this is happening?
Only modify your token_endpoint to https Protocols. E.G:
token_endpoint = 'https://login.microsoftonline.com/%s/oauth2/token' % tenant_id.
You can refer to https://msdn.microsoft.com/en-us/library/azure/dn645543.aspx for more details.
Meanwhile, you can leverage Microsoft Azure Active Directory Authentication Library (ADAL) for Python for acquire the access token in a ease.
You should use HTTPS instead of HTTP for token_endpoint, and you should specify API version too. Here is what you should use.
token_endpoint = 'https://login.microsoftonline.com/%s/oauth2/token?api-version=1.0' % tenant_id