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

◇◆丶佛笑我妖孽 提交于 2019-12-06 07:22:55

问题


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


回答1:


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:

  • jenkins-api/lib/jenkins/connection.rb (see "crumb method);
  • jenkins-api/lib/jenkins/job.rb (see "activate_job" method);


来源:https://stackoverflow.com/questions/43321489/how-to-add-crumb-for-csrf-in-jenkins-via-json-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!