JENKINS REST API禁止抛出403

问题描述 投票:0回答:1

问题陈述

我在云上运行了Jenkins Sever V:2.190.2。在Jenkins Config Security中选择了“登录用户可以做任何事情”权限。因此,这意味着具有有效用户名和密码的用户可以登录到jenkin服务器并执行授权作业。基本上我需要创造工作在Jenkin服务器上通过传递作业名称和jobXml。

尝试以下选项

到目前为止,我已经使用了Github上提供的“ jenkinsci / java-client-api” api。这个api对于Jenkins相关操作来说真的是很好的api,我遵循了READ.md上给出的说明。我创建了Jenkins Server实例,并尝试调用getJenkinVersion()和getJobs()方法,两者都运行良好并按预期返回结果。但是,当我要调用createJob(jobName,jobXml)时,此调用从服务器返回403禁止的错误。

通过深入研究该问题,我发现以下内容:-1.当我将Jenkin安全配置更改为“任何用户可以做任何事情”时,此createJob()方法将起作用,并且我可以创建作业。但是,由于安全限制,不建议使用此选项。2.当我将Jenkin安全配置保留为“已登录用户可以做任何事情”时,createJob()方法将不起作用并返回403禁止错误。在这里,我还注意到,尽管我提供了正确的用户名和密码/令牌(用于登录),但仍从UI登录到Jenkins服务器用户文档中定义的Jenkin服务器实例,当碰到该方法时,将以“ ANONYMOUS USER”身份登录到jenkin。我认为这是返回403错误的根本原因。

以下代码段

**Sample 1**:
        HttpClientBuilder builder = HttpClientBuilder.create();
        JenkinsHttpClient client = new JenkinsHttpClient(uri, builder, "XXX", "XXX");
        JenkinsServer jenkins = new JenkinsServer(client);
        String sourceXML = readFile("src/main/resources/config.xml");
        System.out.println(String.format("Installed Jenkins Version >> %s", jenkins.getVersion().getLiteralVersion()));//works and gives correct result
        jenkins.createJob("test-nov1", sourceXML);

**Sample 2**:
        HttpClientBuilder builder = HttpClientBuilder.create();
        JenkinsHttpClient client = new JenkinsHttpClient(uri, addAuthentication(builder, uri, userName, passwordOrToken));
        JenkinsServer jenkins = new JenkinsServer(client);
        String sourceXML = readFile("src/main/resources/config.xml");
        System.out.println(String.format("Installed Jenkins Version >> %s", jenkins.getVersion().getLiteralVersion()));
        jenkins.createJob(null,"test-nov1", sourceXML,true);

**Sample Exception**:
    Exception in thread "main" org.apache.http.client.HttpResponseException: status code: 403, reason phrase: Forbidden
    at com.offbytwo.jenkins.client.validator.HttpResponseValidator.validateResponse(HttpResponseValidator.java:11)
    at com.offbytwo.jenkins.client.JenkinsHttpClient.post_xml(JenkinsHttpClient.java:375)
    at com.offbytwo.jenkins.JenkinsServer.createJob(JenkinsServer.java:389)
    at com.offbytwo.jenkins.JenkinsServer.createJob(JenkinsServer.java:359)
    at com.xx.OffByTwoJenkins.main(OffByTwoJenkins.java:31)

选项2:我还尝试了其他方法,方法是直接使用HttpUrl连接直接调用Jenkin REST API。

**Sample Code** :
public int createJob(final String username, final String password, final String jenkinsUrl, final String jobName) {
        // http://JENKINSURL//createItem?name=JOBNAME
        String jobUrl = jenkinsUrl + "/createItem?name=" + jobName;

        int responseCode = 00;
        try {
            String basicAuth = Base64.getEncoder().encodeToString((username+":"+password).getBytes(StandardCharsets.UTF_8));
            //String encoding = Base64.getEncoder().encodeToString((username+":"+password).getBytes("utf-8"));
            System.out.println(String.format("User Auth >> %s", basicAuth));
            String sourceXML = readFile("src/main/resources/config.xml");
            URL url = new URL(jobUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            //connection.setReadTimeout(10000);
            //connection.setConnectTimeout(15000);
            connection.setRequestProperty("Authorization", "Basic " + basicAuth);
            connection.setRequestProperty("Content-Type", "application/xml");
            connection.setRequestProperty("Content-Language", "en-US");
            connection.setRequestMethod("POST");
            connection.setUseCaches(false);
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setInstanceFollowRedirects(false);
            OutputStream os = connection.getOutputStream();
            os.write(sourceXML.getBytes());
            os.flush();
            responseCode = connection.getResponseCode();
            BufferedReader br = new BufferedReader(new InputStreamReader((connection.getInputStream())));
            String output;
            System.out.println("Output from Server .... \n");
            while ((output = br.readLine()) != null) {
                System.out.println(output);
            }
            connection.disconnect();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return responseCode;

    }

This also returns with same error 403 forbidden.

**Exception** :
Caused by: java.io.IOException: Server returned HTTP response code: 403 for URL: <<JenkinsURL>>
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
    at java.net.HttpURLConnection.getResponseCode(Unknown Source)
    at com.xx.JenkinsJobExecutor.createJob(JenkinsJobExecutor.java:109)

我真的不明白我需要为获得创造工作而进行调整的地方。谢谢

java rest jenkins http-post jenkins-cli
1个回答
0
投票

当我尝试执行Jenkins API以使用curl运行作业时,我遇到了类似的问题。问题在于,仅提供用于基本身份验证的用户名和密码将不允许您执行操作,因此会出现错误403。您还需要在请求标头中以cookie的形式发送用户特定的信息。

我通过存储cookie并在后续的POST请求中使用它,找到了解决此问题的方法。

我的工作流程如下:

  1. 使用简单的GET请求(以及用户名和密码作为基本身份验证)从Jenkins获取面包屑。 HTTP响应还会在标头中返回cookie。存储此响应。

  2. 使用存储的cookie,向Jenkins API发出POST请求。

尝试在问题中使用类似的方法。

© www.soinside.com 2019 - 2024. All rights reserved.