javascriptjsonjenkinscsrf-protection

How to add crumb for CSRF in Jenkins via JSON / JS


I wanna create via API jobs in Jenkins, but i can't connect couse of CSRF protection in Jenkins. I got a crumb but idk how to attach it to the url/request in JSON or JavaScript to get data pass by POST method. Any ideas? I wanna make it only with JS, without using JAVA. Thanks


Solution

  • It should be easy enough. There are few things you are expected to do in order to get thru CSRF in Jenkins.

    #1

    Fetch an actual CSRF crumb that is valid and for that you should use "/crumbIssuer" endpoint. AFAIK, this is a protected endpoint and therefore you should make an authenticated call to it using either API Token or your credentials in the request. Here how would I do it in JavaScript:

    // **** - is a placeholder for an auth token, replace it with yours
    $.get({
        url: "https://my.jenkins.io/crumbIssuer/api/json",
        contentType: "application/json",
        headers: {
            "User-Agent": "my_js_script",
            "Authorization": "****"
        }
    }).done(function(data) {
        // this is how you fetch valid & actual CSRF crumb
        console.log(data.crumbRequestField + " = " + data.crumb);
    });
    

    #2

    Now, since you've got a handle on a valid & actual CSRF crumb, do send it with any request that modifies state in Jenkins. Lets say, your valid CSRF crumb JSON looks something like this:

    { "crumbRequestField": "Jenkins-Crumb", "crumb": "noop" }
    

    and therefore your Ajax call would look somewhat like this (note an extra "Jenkins-Crumb" HTTP header):

    // **** - is a placeholder for an auth token, replace it with yours
    // simply activates a job in Jenkins, requirement for cloned jobs (aka. "Create-A-Copy-From")
    $.post({
        url: "https://my.jenkins.io/job/my_job/description",
        contentType: "application/x-www-form-urlencoded; charset=UTF-8",
        headers: {
            "User-Agent": "my_js_script",
            "Authorization": "****",
            "Jenkins-Crumb": "noop" // makes CSRF filter in Jenkins happy
        },
        data: "description="
    });
    

    These JavaScript snippets unlikely perfect, but hopefully give you the right direction.

    I'm working on a project that is Jenkins API library, but in Ruby. Here are some of the files that might be of interest in case you need to read some source code that actually does what you're looking for: