HttpClient验证Jenkins

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

我有一个Jenkins 1.515服务器。这被配置为将访问控制委托给servlet容器(独立的Tomcat 6)。我正在使用基于矩阵的安全性,并为用户'foo'的每个操作打勾。 我正在尝试使用HttpClient(4.2.3)来查询构建状态。使用基本的HttpClient身份验证,到目前为止,我有:

DefaultHttpClient httpclient = new DefaultHttpClient();

    httpclient.getCredentialsProvider().setCredentials(
            new AuthScope("dev.mycompany.com", 80), 
            new UsernamePasswordCredentials("foo", "bar"));

    try {

        HttpPost httpost = new HttpPost("http://dev.mycompany.com/jenkins/rssLatest");
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String responseBody = httpclient.execute(httpost, responseHandler);
        System.out.println(responseBody);

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

执行此操作时,结果为:

   Exception in thread "main" org.apache.http.client.HttpResponseException: Forbidden

现在,我尝试使用不同方法通过Google发现许多不同的“示例”来使用HttpClient进行身份验证,但所有这些“示例”都会导致上述相同的错误或“内部服务器错误”。 我需要确定使用HttpClient 4对这个Jenkins实例进行身份验证的确切过程。

java jenkins apache-httpclient-4.x
2个回答
0
投票

在尝试了我可以在Java方法上直接进行身份验证的所有内容之后,我发现wget可以使用“基本”授权工作,然后我使用HttpClient来模仿相同的请求/响应头。这不是我能找到的推荐方法,但它对我有用。例如:

HttpGet httpget = new HttpGet("http://dev.mycompany.com/jenkins/rssLatest?token=MYTOKEN");
            httpget.setHeader("Host", "dev.mycompany.com");
            httpget.setHeader("Connection", "keep-alive");
            httpget.setHeader("Authorization", "Basic USERNAMEandMYTOKENbase64ENCRYPTED=" );

0
投票

原因是Jenkins在您未登录时返回错误403(FORBIDDEN),但HttpClient期望TargetAuthenticationStrategy中的错误401(UNAUTHORIZED)。因此,HttpClient从未注意到Jenkins要求输入密码。

解决此问题的一种方法是使用此处描述的“抢占式身份验证”:https://hc.apache.org/httpcomponents-client-ga/tutorial/html/authentication.html

这将与您的操作相同:始终将“授权”标头添加到请求中。

代码示例的副本:

CloseableHttpClient httpclient = <...>

HttpHost targetHost = new HttpHost("localhost", 80, "http");
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
        new AuthScope(targetHost.getHostName(), targetHost.getPort()),
        new UsernamePasswordCredentials("username", "password"));

// Create AuthCache instance
AuthCache authCache = new BasicAuthCache();
// Generate BASIC scheme object and add it to the local auth cache
BasicScheme basicAuth = new BasicScheme();
authCache.put(targetHost, basicAuth);

// Add AuthCache to the execution context
HttpClientContext context = HttpClientContext.create();
context.setCredentialsProvider(credsProvider);
context.setAuthCache(authCache);

HttpGet httpget = new HttpGet("/");
for (int i = 0; i < 3; i++) {
    CloseableHttpResponse response = httpclient.execute(
            targetHost, httpget, context);
    try {
        HttpEntity entity = response.getEntity();

    } finally {
        response.close();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.