I am trying to build a Python 3 service that calls the ActiveMQ REST management API provided by Jolokia, but I get a 401 Unauthorized
response. My guess is that I am passing the authentication data wrong. Unfortunately, the ActiveMQ REST documentation example with curl
or wget
doesn't really help much.
import urllib.parse
import urllib.request
url = 'http://localhost:8161/api/jolokia/read/org.apache.activemq:type=Broker,brokerName=localhost,service=Health'
data = dict(user='admin', password='admin')
encoded_data = urllib.parse.urlencode(data)
encoded_data = encoded_data.encode('utf-8')
response = urllib.request.urlopen(url, encoded_data)
This is the exception it is raised after the request:
raise HTTPError(req.full_url, code, msg, hdrs, fp) urllib.error.HTTPError: HTTP Error 401: Unauthorized
One way of authenticating successfully is by using urllib2
and python2
and passing user info in the URL but I want to do it the right way and not like this: http://admin:admin@localhost:8161/api/jolokia/read/org.apache.activemq:type=Broker,brokerName=localhost,service=Health
.
To whom it may concern: Since the ActiveMQ REST is using Basic Authorization, the solution is to add the "Basic" authorization header and the login data encoded in base64. Here is my solution:
url = 'http://localhost:8161/api/jolokia/read/org.apache.activemq:type=Broker,brokerName=localhost,service=Health'
request = urllib.request.Request(url)
login_data = "{}:{}".format(username, password) # default: login_data = "admin:admin"
urlsafe_encoded_bytes_login_data = base64.urlsafe_b64encode(login_data.encode("utf-8"))
urlsafe_encoded_str_login_data = str(urlsafe_encoded_bytes_login_data, "utf-8")
request.add_header("Authorization", "Basic {}".format(urlsafe_encoded_str_login_data))
result = urllib.request.urlopen(request)
print(result.status)