Learn to generate and use Jenkins CSRF crumb tokens for securing your Jenkins environment against Cross-Site Request Forgery attacks.
In this lesson, you will learn how to generate and use Jenkins CSRF crumb tokens to secure your Jenkins environment. Previously, we covered API tokens and REST API calls. Today, we focus on CSRF protection in Jenkins and explore how unique crumb tokens help secure requests against Cross-Site Request Forgery attacks.Jenkins protects you by generating a unique, randomly created token (crumb) for each user session. This token is produced by hashing details such as the username, session ID, IP address, and a unique Jenkins salt. When a submission is made, these details must match for the crumb to be considered valid.
Jenkins enables CSRF protection by default. It is highly recommended to keep this protection enabled to prevent unauthorized requests.
By default, CSRF protection is enabled in Jenkins. Administrators can verify the settings by navigating to Manage Jenkins > Configure Global Security. In the security configuration, look for the CSRF protection settings, as shown in the image below:
If necessary, it is possible to disable CSRF protection by setting the following system property:
Once you have the crumb token and session cookie, you can trigger a Jenkins job. Consider a parameterized pipeline job named “parameterized-pipeline-job.” Use the following cURL command to send a POST request that includes the crumb header, cookie, and necessary parameters:
After executing the command, a new build will be triggered in Jenkins, confirming that the crumb token and session cookie are correctly configured for secure REST API calls.
Using API tokens is an alternative authentication method that bypasses CSRF protection. When you authenticate with your username and API token, the CSRF crumb mechanism is not required, simplifying your API interactions.
This lesson provided a step-by-step guide to understanding and using Jenkins CSRF crumb tokens. By following these best practices, you ensure that all your API interactions with Jenkins are secure. For more detailed information, refer to the Jenkins Documentation.Happy Coding!