How to Use CSRF Protection in Jenkins: Simple Guide
To use
CSRF protection in Jenkins, enable the Prevent Cross Site Request Forgery exploits option in Manage Jenkins > Configure Global Security. Jenkins then requires a special token with each request to block unauthorized actions.Syntax
Jenkins CSRF protection is configured via the web interface, not by code syntax. The key setting is:
- Prevent Cross Site Request Forgery exploits: A checkbox in Jenkins security settings.
- When enabled, Jenkins adds a
crumbtoken to requests to verify they come from trusted sources.
API or script calls must include this crumb token in headers or parameters to succeed.
bash
curl -u username:api_token -H "Jenkins-Crumb: crumb_value" http://jenkins-server/job/job-name/build
Example
This example shows how to get the CSRF crumb token and use it to trigger a Jenkins job via the REST API.
bash
CRUMB=$(curl -u user:token 'http://jenkins-server/crumbIssuer/api/xml?xpath=concat(//crumbRequestField,":",//crumb)') curl -u user:token -H "$CRUMB" -X POST http://jenkins-server/job/example-job/build
Output
Triggered build for job 'example-job' successfully.
Common Pitfalls
- Not enabling CSRF protection leaves Jenkins vulnerable to attacks.
- API calls without the crumb token will fail with 403 Forbidden errors.
- Using outdated plugins or Jenkins versions may cause crumb issues.
- Remember to update scripts to fetch and include the crumb token dynamically.
bash
curl -u user:token -X POST http://jenkins-server/job/example-job/build # Fails with 403 Forbidden # Correct way: CRUMB=$(curl -u user:token 'http://jenkins-server/crumbIssuer/api/xml?xpath=concat(//crumbRequestField,":",//crumb)') curl -u user:token -H "$CRUMB" -X POST http://jenkins-server/job/example-job/build
Quick Reference
Steps to enable and use CSRF protection in Jenkins:
- Go to
Manage Jenkins > Configure Global Security. - Check
Prevent Cross Site Request Forgery exploits. - Save the settings.
- For API calls, fetch the crumb token from
/crumbIssuer/api/xml. - Include the crumb token in your request headers or parameters.
Key Takeaways
Always enable CSRF protection in Jenkins security settings to prevent attacks.
API and script requests must include the crumb token to be accepted.
Fetch the crumb token dynamically from Jenkins before making API calls.
Without the crumb token, Jenkins will reject POST requests with 403 errors.
Keep Jenkins and plugins updated to avoid CSRF-related issues.