如何申请詹金斯的面包屑发行人

Sat*_*ish 28 security api jenkins

我想使用Jenkins Remote API,我正在寻找安全的解决方案.我遇到了Prevent Cross Site Request Forgery exploits,我想使用它,但我读到某个地方,你必须提出碎屑请求.

如何获取crumb请求以使API正常工作?

我发现了这个https://github.com/entagen/jenkins-build-per-branch/pull/20,但我仍然不知道如何解决它.

我的Jenkins版本是1.50.x.

使用POST请求时,经过身份验证的远程API请求以403响应

che*_*ffe 33

我也没有在文档中找到这个.此代码针对较旧的Jenkins(1.466)进行了测试,但仍应有效.

发出面包屑使用 crumbIssuer

// left out: you need to authenticate with user & password -> sample below
HttpGet httpGet = new HttpGet(jenkinsUrl + "crumbIssuer/api/json");
String crumbResponse = toString(httpclient, httpGet);
CrumbJson crumbJson = new Gson().fromJson(crumbResponse, CrumbJson.class);
Run Code Online (Sandbox Code Playgroud)

这会得到这样的回复

{"crumb":"fb171d526b9cc9e25afe80b356e12cb7","crumbRequestField":".crumb"}
Run Code Online (Sandbox Code Playgroud)

这包含您需要的两条信息

  1. 您需要传递碎屑的字段名称
  2. 面包屑本身

如果您现在想要从Jenkins中获取内容,请将crumb添加为标题.在下面的示例中,我获取最新的构建结果.

HttpPost httpost = new HttpPost(jenkinsUrl + "rssLatest");
httpost.addHeader(crumbJson.crumbRequestField, crumbJson.crumb);
Run Code Online (Sandbox Code Playgroud)

以下是整个示例代码.我正在使用gson 2.2.4来解析响应和Apache的httpclient 4.2.3.

import org.apache.http.auth.*;
import org.apache.http.client.*;
import org.apache.http.client.methods.*;
import org.apache.http.impl.client.*;

import com.google.gson.Gson;

public class JenkinsMonitor {

    public static void main(String[] args) throws Exception {

        String protocol = "http";
        String host = "your-jenkins-host.com";
        int port = 8080;
        String usernName = "username";
        String password = "passwort";

        DefaultHttpClient httpclient = new DefaultHttpClient();
        httpclient.getCredentialsProvider().setCredentials(
                new AuthScope(host, port), 
                new UsernamePasswordCredentials(usernName, password));

        String jenkinsUrl = protocol + "://" + host + ":" + port + "/jenkins/";

        try {
            // get the crumb from Jenkins
            // do this only once per HTTP session
            // keep the crumb for every coming request
            System.out.println("... issue crumb");
            HttpGet httpGet = new HttpGet(jenkinsUrl + "crumbIssuer/api/json");
            String crumbResponse= toString(httpclient, httpGet);
            CrumbJson crumbJson = new Gson()
                .fromJson(crumbResponse, CrumbJson.class);

            // add the issued crumb to each request header
            // the header field name is also contained in the json response
            System.out.println("... issue rss of latest builds");
            HttpPost httpost = new HttpPost(jenkinsUrl + "rssLatest");
            httpost.addHeader(crumbJson.crumbRequestField, crumbJson.crumb);
            toString(httpclient, httpost);

        } finally {
            httpclient.getConnectionManager().shutdown();
        }

    }

    // helper construct to deserialize crumb json into 
    public static class CrumbJson {
        public String crumb;
        public String crumbRequestField;
    }

    private static String toString(DefaultHttpClient client, 
        HttpRequestBase request) throws Exception {
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String responseBody = client.execute(request, responseHandler);
        System.out.println(responseBody + "\n");
        return responseBody;
    }

}
Run Code Online (Sandbox Code Playgroud)


Joh*_*hee 8

此 Python 函数获取 crumb,并另外使用 crumb 发布到 Jenkins 端点。这是在 Jenkins 2.46.3 上测试的,并且打开了CSRF 保护:

import urllib.parse
import requests

def build_jenkins_job(url, username, password):
    """Post to the specified Jenkins URL.

    `username` is a valid user, and `password` is the user's password or
    (preferably) hex API token.
    """
    # Build the Jenkins crumb issuer URL
    parsed_url = urllib.parse.urlparse(url)
    crumb_issuer_url = urllib.parse.urlunparse((parsed_url.scheme,
                                                parsed_url.netloc,
                                                'crumbIssuer/api/json',
                                                '', '', ''))
    # Use the same session for all requests
    session = requests.session()

    # GET the Jenkins crumb
    auth = requests.auth.HTTPBasicAuth(username, password)
    r = session.get(crumb_issuer_url, auth=auth)
    json = r.json()
    crumb = {json['crumbRequestField']: json['crumb']}

    # POST to the specified URL
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    headers.update(crumb)
    r = session.post(url, headers=headers, auth=auth)

username = 'jenkins'
password = '3905697dd052ad99661d9e9f01d4c045'
url = 'http://jenkins.example.com/job/sample/build'
build_jenkins_job(url, username, password)
Run Code Online (Sandbox Code Playgroud)

  • 这对我不起作用。它在邮递员那里工作。我必须调用端点来生成面包屑并将其添加到 POST 中。我对上面的 Python 代码做了类似的操作,但不知何故我收到了 403 错误。 (2认同)

Jam*_*esD 5

或者您可以使用Python requests代替

req = requests.get('http://JENKINS_URL/crumbIssuer/api/xml?xpath=concat(//crumbRequestField,":",//crumb)', auth=(username, password))
print(req.text)
Run Code Online (Sandbox Code Playgroud)

会给你名字和面包屑:

Jenkins-Crumb:e2e41f670dc128f378b2a010b4fcb493
Run Code Online (Sandbox Code Playgroud)