authentication with urllib3 - python

I am trying to connect to a webpage using urllib3. The code is provided below.
import urllib3
http=urllib3.PoolManager()
fields={'username':'abc','password':'xyz'}
r=http.request('GET',url,fields)
If we assume that url is some webpage which needs to be authenticated using username and password, am i using the right code to authenticate ?
I have did this using urllib2 very comfortably but i was not able to do the same thing using urllib3.
Many Thanks

Assuming you're trying to do Basic Authentication, then you need to put the username and password encoded in an Authorization header. Here's one way to do that using the urllib3.make_headers helper:
import urllib3
http = urllib3.PoolManager()
url = '...'
headers = urllib3.make_headers(basic_auth='abc:xyz')
r = http.request('GET', url, headers=headers)

Below is a working example to authenticate to an API using the requests library (ubuntu with python 3.6). Hope it helps!
import json
import requests
from requests.auth import HTTPBasicAuth
def __init__(self):
header = {"Content-Type": "application/json"}
access_url = "https://your.login.url/context_path"
data = {
"key_to_send":"value_to_send"
}
def get_token(self):
self.data = json.dumps(self.data)
encoded_data = json.dumps(self.data).encode('utf-8')
self.response = requests.post(self.access_url, auth=HTTPBasicAuth(self.username, self.password), headers=self.header, data=self.data)
# Show me what you found
print(self.response.text)

Related

How to i make domain authorization in Thycotic

I need some help on authorizing in Thycotic using current domain authorization via its API (no need to enter domain username and pass).
So the Thycotic API has this possibility, but i dont understand how to use it. In it manual i see some example, but using PS
$api = "https://<Secret Server URL>/winauthwebservices/api/v1"
$endpoint = "$api/secrets/8387"
$secret = Invoke-RestMethod $endpoint -UseDefaultCredentials
In my python script i'm trying with sspi
from requests_negotiate_sspi import HttpNegotiateAuth
site = 'https://<Secret Server URL>/SecretServer'
windows_auth_API = '/winauthwebservices/api/v1'
headers = {'Accept':'application/json', 'content-type':'application/x-www-form-urlencoded'}
how do i make the further login here? resp gives me 401: Unauthorized
resp = requests.post(site+windows_auth_API, headers=headers, auth=HttpNegotiateAuth)
the solution
from requests_negotiate_sspi import HttpNegotiateAuth
import requests
site = 'https://<Secret Server URL>/SecretServer'
windows_auth_API = '/winauthwebservices/api/v1'
resp = requests.get(site+windows_auth_API+"/secrets/8387", auth=HttpNegotiateAuth())

How to Manually craft the Authorization header for Github in Python?

Im using requests Python module to access Github's API. Github responses 404 Not Found, as expected.
This is my code:
import requests
import sys
username = sys.argv[1]
password = sys.argv[2]
url = 'https://api.github.com/{}'.format(username)
print(url)
response = requests.get(url, data={'password': password})
print(response)
How this header must be done?
I need to get the user's id!
Thanks!

Oauth1.0: How to generate HMAC-SHA1 Oauth_signature without using Access token and token secret in python?

I am trying to access a resource for which I have to implement Oauth1 authorization. When I am using from postman with the option to add empty parameters to signature its working fine but when I am trying to implement the same thing with Python its throwing error.
This is my python code So please tell me what are the changes i have to make
import requests
import json
from requests_oauthlib import OAuth1Session
from requests_oauthlib import OAuth1
import urllib
import random
import time
from hashlib import sha1
import hmac
def sign_request(epocTime,nounce):
key = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX'
url = "GET&https://XXXXXXXXXXXXXXXXXXXXX/api/XXXXXXXXXXXXX&oauth_consumer_key=XXXXXXX&oauth_nonce=12345&oauth_signature_method=HMAC-SHA1&oauth_timestamp={}&oauth_version=1.0".format(epoch_time)
raw = urllib.quote(url)
hashed = hmac.new(key, raw, sha1)
print hashed
return hashed.digest().encode("base64")
def test():
nounce = "12345"
epoch_time = int(time.time())
url = "https://XXXXXXXXXXXXXX/api/XXXXXXXXXXXXXXXXXXXXXX"
strr = sign_request(epoch_time,nounce)
print strr
querystring = {"oauth_consumer_key":"1XXXXXXXXXXXXXXXXX","oauth_token":"",
"oauth_signature_method":"HMAC-SHA1","oauth_timestamp":epocTime,
"oauth_nonce":nounce,"oauth_version":"1.0",
"oauth_signature":strr}
response = requests.request("GET", url, params=querystring)
print response.text
test()
I was having a similar issue in Python 3...trying to use OAuth 1.0 for a site that didn't use tokens. The hardest part for me was getting the right signature. This answer got me where I needed to be.

Sending authenticated multipart/form-data request using Python Requests

Using Python and Requests, I am trying to upload a file to an API using multipart/form-data POST requests with a custom authentication mechanism (Just adding an 'Authentication-Token' header).
Here is the code I use:
import requests
from requests.auth import AuthBase
class MyAuth(AuthBase):
def __init__(self, token):
self.token = token
def __call__(self, r):
r.headers['Authentication-Token'] = self.token
return r
token = "175a5607d2e79109539b490f0f8ffe60"
url = "https://my-ap.com/files"
r = requests.post(url,
files={'file': open('qsmflkj.jpg', 'rb')},
data={'id': 151},
auth=MyAuth(token)
)
Unfortunately, this request causes the following exception on the server (the backend is using the Spring framework) :
org.apache.tomcat.util.http.fileupload.FileUploadException: the request was rejected because no multipart boundary was found
I have tried a lot of things, like adding the header myself, but this seems to be the "right" way to do it, and it fails. I know that the API is used from various mobile clients, and hence, that it is possible to upload picture there. What could I do differently to be able to use this API in Python?
In the end, I never managed to do this with Requests, but I succeeded with urllib2 and the poster library:
from poster.encode import multipart_encode
from poster.streaminghttp import register_openers
import urllib2
register_openers()
token = "175a5607d2e79109539b490f0f8ffe60"
with open('qsmflkj.jpg', 'rb') as f:
datagen, headers = multipart_encode({"file": f})
headers['Authentication-Token'] = token
request = urllib2.Request("https://myserver.com/files", \
datagen, headers)
response = urllib2.urlopen(request)

REST GET request on Python sending named argument

I am playing from Linux using curl inside bash but now I need to move my script to python in order to be more effective.
What is the best way to do something like the following line on python?
curl baseuri:port/resource -u user:pswd
I played already with urllib2 but I dont get a clue on how to send the "-u user:pswd"
You'll need to use a HTTPPasswordMgrWithDefaultRealm instance to handle the authentication, and add in a HTTPBasicAuthHandler handler to respond to the authentication challenge:
import urllib2
url = 'baseuri:port/resource'
username = 'user'
password = 'pswd'
pwmgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
pwmgr.add_password(None, url, username, password)
authhandler = urllib2.HTTPBasicAuthHandler(passman)
opener = urllib2.build_opener(authhandler)
response = opener.open(theurl)
Yes, this is a handful.
If you can install a 3rd party library, then add use the requests library; it'll be so much easier:
import requests
url = 'baseuri:port/resource'
username = 'user'
password = 'pswd'
response = requests.get(url, auth=(username, password))
Actually, we use pycurl instead which also works pretty well. Here an example to get a json from the request:
import pycurl
import json
from io import BytesIO
data = BytesIO()
pyCurl = pycurl.Curl()
pyCurl.setopt(pyCurlClass.URL,string_http)
pyCurl.setopt(pycurl.USERPWD, 'user:password')
pycurl.setopt(c.WRITEFUNCTION, data.write)
pyCurl.perform()
dictionary = json.loads(data.getvalue())

Categories

Resources