1

我有一个 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

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

4

2 回答 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=" );
于 2013-08-22T01:45:37.887 回答
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();
    }
}
于 2019-03-04T14:00:18.633 回答