Basic Authentication Using Urllib2 With Python With Jira Rest Api
Solution 1:
I'd recommend considering using the very excellent requests
library which provides a nice abstraction to make urllib2 a bit easier to use.
With requests
you can simply do:
r = requests.get('https://api.github.com', auth=('user', 'pass'))
It supports all of the request methods needed to make REST calls as well (POST, PUT, DELETE, etc...).
You can find more here:
http://pypi.python.org/pypi/requests
If you absolutely MUST use plain old urllib2, here is an example of how it can be done:
import urllib2
theurl = 'http://www.someserver.com/toplevelurl/somepage.htm'
username = 'johnny'
password = 'XXXXXX'
passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, theurl, username, password)
# because we have put None at the start it will always# use this username/password combination for urls# for which `theurl` is a super-url
authhandler = urllib2.HTTPBasicAuthHandler(passman)
opener = urllib2.build_opener(authhandler)
urllib2.install_opener(opener)
# All calls to urllib2.urlopen will now use our handler# Make sure not to include the protocol in with the URL, or# HTTPPasswordMgrWithDefaultRealm will be very confused.# You must (of course) use it when fetching the page though.
pagehandle = urllib2.urlopen(theurl)
# authentication is now handled automatically for us
More can be found here: http://www.voidspace.org.uk/python/articles/authentication.shtml
Solution 2:
Funny, I was working on this yesterday for the JIRA Python CLI. I took the approach of using the REST API to get an authentication cookie and a custom opener. The example below shows using the opener to post data to a page to add a component, but you could replace that with a call to the correct URL for a different REST call.
"""
Demonstration of using Python for a RESTful call to JIRA
Matt Doar
CustomWare
"""
import urllib
import urllib2
import cookielib
jira_serverurl = "http://jira.example.com:8080"
creds = { "username" : "admin", "password" : "admin" }
authurl = jira_serverurl + "/rest/auth/latest/session"# Get the authentication cookie using the REST API
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
req = urllib2.Request(authurl)
req.add_data('{ "username" : "admin", "password" : "admin" }')
req.add_header("Content-type", "application/json")
req.add_header("Accept", "application/json")
fp = opener.open(req)
fp.close()
add_component_url = jira_serverurl + "/secure/project/AddComponent.jspa?pid=10020&name=ABC4"
print "Using %s" % (add_component_url)
# Have to add data to make urllib2 send a POST
values = {}
data = urllib.urlencode(values)
# Have to tell JIRA to not use a form token
headers = {'X-Atlassian-Token': 'no-check'}
request = urllib2.Request(add_component_url, data, headers=headers)
fp = opener.open(request)
print fp.read()
Solution 3:
I had better success using the requests module.
import requests
jira_session = requests.session()
try:
jira_session.post('https://server', auth=(user, password), verify=False)
except:
print('Unable to connect or authenticate with JIRA server.')
url = 'https://server/rest/api/2/search?jql=project="ABCXYZ"&maxResults=100'
results = jira_session.get(url)
project_data = results.json()
Solution 4:
I had the same problem with accessing Jira REST. Here is what worked for me:
classJiraOpenerWrapper(object):
# Class to wrap urllib2 OpenerDirector to add authenication headers.# this is needed fro Jira - see comment below.def__init__(self, opener, user, password):
self.opener = opener
self.user = user
self.password = password
defopen(self, url, data, timeout):
ifisinstance(url, str):
# if given a url - create a request and add
req = urllib2.Request(url, data, {
"Authorization":
"Basic " + base64.b64encode(
self.user + ":" + self.password)
})
else:
req = url
return self.opener.open(req, data, timeout)
def__getattr__(self, attr):
if attr == "open":
return self.openreturngetattr(self.opener, attr)
defRegisterPasswords(user, password):
password_manager = urllib2.HTTPPasswordMgrWithDefaultRealm()
password_manager.add_password(
None, 'https://rt.mycorp.site/', user, password)
password_manager.add_password(
None, 'https://jira.mycorp.site/', user, password)
auth_handler = urllib2.HTTPBasicAuthHandler(password_manager)
opener = urllib2.build_opener(auth_handler)
# Jira has a strage behviour - it does not return the proper error # when sending a request without an Authentication header.# This causes Python's urllib2 not to retry with the pass word.# For Jira we would need to add the headers all the time
jira_opener = JiraOpenerWrapper(opener, user, password)
urllib2.install_opener(jira_opener)
defGameJira():
url = "https://jira.mycorp.site/rest/api/2/issue/PRJ-123"
data = urllib2.urlopen(url, None).read()
print"Jira:\n", data
Post a Comment for "Basic Authentication Using Urllib2 With Python With Jira Rest Api"