Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python, HTTPS GET with basic authentication

Im trying to do a HTTPS GET with basic authentication using python. Im very new to python and the guides seem to use diffrent librarys to do things. (http.client, httplib and urllib). Can anyone show me how its done? How can you tell the standard library to use?

like image 429
Tom Squires Avatar asked Aug 09 '11 16:08

Tom Squires


People also ask

How do you pass basic auth in header in Python?

You'll need to import the following first. Part of the basic authentication header consists of the username and password encoded as Base64. In the HTTP header you will see this line Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ= . The encoded string changes depending on your username and password.

Is Basic Auth secure with https?

Note: The HTTP basic authentication scheme can be considered secure only when the connection between the web client and the server is secure. If the connection is insecure, the scheme does not provide sufficient security to prevent unauthorized users from discovering the authentication information for a server.


1 Answers

In Python 3 the following will work. I am using the lower level http.client from the standard library. Also check out section 2 of rfc2617 for details of basic authorization. This code won't check the certificate is valid, but will set up a https connection. See the http.client docs on how to do that.

from http.client import HTTPSConnection from base64 import b64encode #This sets up the https connection c = HTTPSConnection("www.google.com") #we need to base 64 encode it  #and then decode it to acsii as python 3 stores it as a byte string userAndPass = b64encode(b"username:password").decode("ascii") headers = { 'Authorization' : 'Basic %s' %  userAndPass } #then connect c.request('GET', '/', headers=headers) #get the response back res = c.getresponse() # at this point you could check the status etc # this gets the page text data = res.read()   
like image 185
Andrew Cox Avatar answered Oct 07 '22 05:10

Andrew Cox