Skip to content Skip to sidebar Skip to footer

How To Authenticate In Jenkins While Remotely Accessing Its Json Api?

I need to access the Jenkins JSON API from a Python script. The problem is that our Jenkins installation is secured so to log in users have to select a certificate. Sadly, in Jenki

Solution 1:

You have to authenticate to the JSON API using HTTP Basic Auth.

To make scripted clients (such as wget) invoke operations that require authorization (such as scheduling a build), use HTTP BASIC authentication to specify the user name and the API token. This is often more convenient than emulating the form-based authentication

https://wiki.jenkins-ci.org/display/JENKINS/Authenticating+scripted+clients

Here is a sample of using Basic Auth with Python.

http://docs.python-requests.org/en/master/user/authentication/

Keep in mind if you are using a Self Signed certificate on an internal Jenkin Server you'll need to turn off certificate validation OR get the certificate from the server and add it to the HTTP request

http://docs.python-requests.org/en/master/user/advanced/

Solution 2:

I finally found out how to authenticate to Jenkins using certs and wget. I had to convert my pfx certificates into pem ones with cert and keys in separate files For more info about that come here. In the end this is the command I used.

wget --certificate=/home/B/cert.pem --private-key=/home/B/key.pem --no-check-certificate --output-document=jenkins.jsonhttps:<URL>

Solution 3:

I'm not completely sure it covers your certificate use case, but since it took me some time to find out, I still want to share this snipped that retrieves the email address for a given user name in Python without special Jenkins libraries. It uses an API token and "supports" (actually ignores) https:

def _get_email_adress(user):
    request = urllib.request.Request("https://jenkins_server/user/"+ user +"/api/json")
    #according to https://stackoverflow.com/a/28052583/4609258 the following is ugly
    context = ssl._create_unverified_context() 
    base64string = base64.b64encode(bytes('%s:%s' % ('my user name', 'my API token'),'ascii'))
    request.add_header("Authorization", "Basic %s" % base64string.decode('utf-8'))

    with urllib.request.urlopen(request, context=context) as url:
        user_data = json.loads(url.read().decode())
        for property in user_data['property']:
            if property["_class"]=="hudson.tasks.Mailer$UserProperty":
                return property["address"];

Post a Comment for "How To Authenticate In Jenkins While Remotely Accessing Its Json Api?"