How to get the API Token for Jenkins

Viewed 126798

I am trying to use the jenkins rest api. In the instructions it says I need to have the api key. I have looked all over the configuration pages to find it. How do i get the API key for jenkins?

4 Answers

The non UI way to do this post Jenkins 2.129 is:

curl 'https://<jenkinsURL>/me/descriptorByName/jenkins.security.ApiTokenProperty/generateNewToken' \
--data 'newTokenName=foo' \
--user username:Password

which returns:

{
  "status": "ok",
  "data": {
    "tokenName": "foo",
    "tokenUuid": "<uuid>",
    "tokenValue": "<redacted>"
  }
}

Pre Jenkins 2.129

curl http://<username>:<password>@<jenkins-url>/me/configure 

Tested in Jenkins 2.225

After making research for several hours I could find the answer:

Api Token is used instead of CSFR token. However, what happens if you want to make authentication from any other client(POSTMAN, CLI. curl, etc).

First you need to get a CSFR token and save the information in a cookie with --cookie-jar

  • REQUEST

curl -s --cookie-jar /tmp/cookies -u username:password http://localhost:8080/crumbIssuer/api/json

  • RESPONSE

{ "_class": "hudson.security.csrf.DefaultCrumbIssuer", "crumb": "bc92944100d12780cfc251c9255f3f323a475562b4ee0d8b9cc6e4121f50a450", "crumbRequestField": "Jenkins-Crumb" }

Then we can read the cookie with --cookie and generate the new token:

  • REQUEST

curl -X POST -H 'Jenkins-Crumb:your_crumb_token_generated_above' --cookie /tmp/cookies http://localhost:8080/me/descriptorByName/jenkins.security.ApiTokenProperty/generateNewToken?newTokenName=\your_token_name -u username:password

  • RESPONSE

{ "status": "ok", "data": { "tokenName": "my android token", "tokenUuid": "c510e26c-b2e8-4021-bf79-81d1e4c112af", "tokenValue": "11a2a0c91913d1391d8e8cb155ca714581" } }

How to Generate Jenkins API Token

Following commands need curl and jq. Execute in the same session.

# Change the following appropriately
JENKINS_URL="http://localhost:8080"
JENKINS_USER=admin
JENKINS_USER_PASS=admin

Get the Crumb

JENKINS_CRUMB=$(curl -u "$JENKINS_USER:$JENKINS_USER_PASS" -s --cookie-jar /tmp/cookies $JENKINS_URL'/crumbIssuer/api/xml?xpath=concat(//crumbRequestField,":",//crumb)')

Get the Access token

ACCESS_TOKEN=$(curl -u "$JENKINS_USER:$JENKINS_USER_PASS" -H $JENKINS_CRUMB -s \
                    --cookie /tmp/cookies $JENKINS_URL'/me/descriptorByName/jenkins.security.ApiTokenProperty/generateNewToken' \
                    --data 'newTokenName=GlobalToken' | jq -r '.data.tokenValue')

Cosecutive API calls

Instead of the password, you need to use the token with the username along with the crumb that was generated.

curl -u $JENKINS_USER:$ACCESS_TOKEN \
    -H $JENKINS_CRUMB \ ..........

Related