It sounds like you're encountering issues due to Jenkins' CSRF (Cross-Site Request Forgery) protection, which requires a security token (often called a "crumb") to be included in POST requests. When you access the Jenkins API via your browser, your session includes this crumb, allowing requests to work temporarily. However, when using curl, you need to explicitly handle authentication and include the crumb in your requests.
Here's how you can resolve this:
1. Use an API Token Instead of a Password
First, ensure you're using an API token for authentication instead of your password. Jenkins disallows the use of user passwords for API authentication to enhance security.
- Generate an API Token:
- In Jenkins, click on your username (usually on the top right).
- Click "Configure" from the dropdown.
- Under "API Token", click "Add new Token".
- Give it a name and click "Generate".
- Copy the generated token (you won't be able to see it again).
2. Obtain a CSRF Crumb
You'll need to fetch the CSRF crumb before making API requests. You can get it by accessing the /crumbIssuer/api/json endpoint.
CRUMB=$(curl -s 'http://your-jenkins.com/crumbIssuer/api/json' \
--user 'your_username:your_api_token' | \
grep -oE '"crumb":"[^"]+' | \
cut -d':' -f2 | tr -d '"')
This command does the following:
- Fetches the JSON containing the crumb.
- Extracts the crumb value using
grep and cut.
- Stores the crumb in the
CRUMB variable.
3. Make Authenticated Requests with the Crumb
Include both the authentication and the crumb in your curl requests:
curl -X POST 'http://your-jenkins.com/your/api/endpoint' \
--user 'your_username:your_api_token' \
-H "Jenkins-Crumb:$CRUMB" \
-d "your_data"
-X POST specifies the request method (change as needed).
--user 'your_username:your_api_token' provides authentication.
-H "Jenkins-Crumb:$CRUMB" includes the crumb in the header.
-d "your_data" includes any data you need to send.
Example: Trigger a Jenkins Job
CRUMB=$(curl -s 'http://your-jenkins.com/crumbIssuer/api/json' \
--user 'your_username:your_api_token' | \
grep -oE '"crumb":"[^"]+' | \
cut -d':' -f2 | tr -d '"')
curl -X POST 'http://your-jenkins.com/job/your_job/build' \
--user 'your_username:your_api_token' \
-H "Jenkins-Crumb:$CRUMB"
4. Automate the Process
You can combine these steps into a script or function to automate the process, especially if you'll be making frequent API calls.
Alternative: Disable CSRF Protection for API Tokens (Not Recommended)
If you prefer not to deal with crumbs, you can adjust Jenkins' security settings to exempt API token-based authentication from CSRF protection:
- Go to Manage Jenkins → Configure Global Security.
- Under CSRF Protection, uncheck Prevent Cross Site Request Forgery exploits.
- Note: Disabling CSRF protection is not recommended as it reduces security.
Summary
By properly authenticating your curl requests and including the CSRF crumb, you can interact with the Jenkins API without needing to visit it in your browser first.
References: