Skip to content

Instantly share code, notes, and snippets.

@hmm01i
Created May 16, 2017 19:48
Show Gist options
  • Save hmm01i/0b969b378e3b2455ff2ed7c2405f43bd to your computer and use it in GitHub Desktop.
Save hmm01i/0b969b378e3b2455ff2ed7c2405f43bd to your computer and use it in GitHub Desktop.
Example of urllib with basic auth
# just an example for me to remember
import urllib2, base64
username = "testuser"
password = "changeme"
url = "https://example.com/"
request = urllib2.Request(url)
b64auth = base64.standard_b64encode("%s:%s" % (username,password))
request.add_header("Authorization", "Basic %s" % b64auth)
result = urllib2.urlopen(request)
print(result.read())
@elenalape
Copy link

I just wanted to say that this thing just saved my life. I spent HOURS searching for things on stackoverflow and python docs on how to do basic authentication using the standard libraries. Thank you. <3

@okailiang
Copy link

good

@bezborodow
Copy link

Example for Python3 using the new urllib.

from urllib import request
import base64


username = "testuser"
password = "changeme"
url = "https://example.com/"

b64auth = base64.standard_b64encode(('%s:%s' % (username, password)).encode()).decode()
headers = {
    'Authorization': 'Basic %s' % b64auth
}
req = request.Request(url, headers=headers)
resp = request.urlopen(req)
print(resp.read().decode('utf-8'))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment