HttpClient验证Jenkins

时间:2013-08-21 12:36:24

标签: java jenkins apache-httpclient-4.x

我有一台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实例进行身份验证的过程。

2 个答案:

答案 0 :(得分: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=" );

答案 1 :(得分: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();
    }
}