How to Use API Token in Jenkins for Secure Authentication
In Jenkins, use your
API Token as a password when authenticating via scripts or REST API calls. You combine your Jenkins username with the API token in basic authentication headers or tools like curl to securely access Jenkins without using your actual password.Syntax
To use the API token in Jenkins, you authenticate with your Jenkins username and the API token as the password. This is commonly done in HTTP basic authentication headers.
Example syntax for a curl command:
curl -u <username>:<api_token> <jenkins_url>/job/<job_name>/build
Here:
<username>is your Jenkins username.<api_token>is your personal API token from Jenkins.<jenkins_url>is your Jenkins server URL.<job_name>is the name of the Jenkins job you want to trigger.
bash
curl -u <username>:<api_token> http://jenkins.example.com/job/<job_name>/buildExample
This example shows how to trigger a Jenkins job named TestJob using curl with your API token for authentication.
bash
curl -X POST -u alice:1234abcd5678efgh http://jenkins.example.com/job/TestJob/build
Output
Started build for job TestJob
Common Pitfalls
- Using your Jenkins password instead of the API token can cause authentication failures.
- Not URL-encoding special characters in the API token may break the request.
- For Jenkins instances behind proxies or with CSRF protection, you may need to include a crumb token in your request headers.
- Using the API token in public scripts without protection risks exposing your credentials.
bash
curl -u alice:myPassword http://jenkins.example.com/job/TestJob/build # Wrong: Use API token instead curl -u alice:1234abcd5678efgh http://jenkins.example.com/job/TestJob/build # Correct
Quick Reference
| Action | Usage Example | Notes |
|---|---|---|
| Get API Token | Jenkins > User > Configure > Show API Token | Generate or copy your token here |
| Use API Token in curl | curl -u username:api_token URL | Authenticate without password |
| Trigger Job | curl -X POST -u user:token http://jenkins/job/jobname/build | Start Jenkins job remotely |
| Handle CSRF | Add crumb header if enabled | Use Jenkins crumb issuer API |
Key Takeaways
Use your Jenkins username and API token as password for API authentication.
Never use your Jenkins password in scripts; always use the API token.
Include CSRF crumb headers if Jenkins has CSRF protection enabled.
Keep your API token secret and avoid exposing it in public code.
You can find or reset your API token in your Jenkins user configuration.