【问题标题】:Apache HttpClient, basic auth and session cookieApache HttpClient、基本身份验证和会话 cookie
【发布时间】:2018-12-05 10:43:54
【问题描述】:

我想调用需要基本身份验证的 Web 服务。我不能使用抢先式身份验证,因为该服务返回带有特定 cookie 的代码 401。此 cookie 必须与基本身份验证标头一起在响应中发送。以下代码不起作用:

    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    Credentials credentials = new UsernamePasswordCredentials("user", "password");
    credentialsProvider.setCredentials(AuthScope.ANY, credentials);

    RequestConfig requestConfig = RequestConfig.custom()
            .setCookieSpec(CookieSpecs.DEFAULT)
            .build();

    HttpClient httpClient = HttpClientBuilder.create()
            .setDefaultCredentialsProvider(credentialsProvider)
            .setDefaultRequestConfig(requestConfig)
            .build();

    HttpGet get = new HttpGet("https://a.something.com/something");
    try {
        HttpResponse response = httpClient.execute(get);
        System.out.println(response.getStatusLine());
    } catch (IOException e) {
        e.printStackTrace();
    }

在日志中,我可以看到 HttpClient 对代码 401 做出反应,并且它正在第二次发送带有基本身份验证数据的请求。但是cookie不见了:

http-outgoing-0 >> "GET /something HTTP/1.1[\r][\n]"
http-outgoing-0 >> "Host: a.something.com[\r][\n]"
http-outgoing-0 >> "Connection: Keep-Alive[\r][\n]"
http-outgoing-0 >> "User-Agent: Apache-HttpClient/4.5.5 (Java/1.8.0_172)[\r][\n]"
http-outgoing-0 >> "[\r][\n]"
http-outgoing-0 << "HTTP/1.1 401 Unauthorized[\r][\n]"
http-outgoing-0 << "WWW-authenticate: basic realm="XXXXXX"[\r][\n]"
http-outgoing-0 << "Set-Cookie: SMCHALLENGE=YES; path=/; domain=.something.com; secure; HTTPOnly[\r][\n]"
http-outgoing-0 >> "GET /something HTTP/1.1[\r][\n]"
http-outgoing-0 >> "Host: a.something.com[\r][\n]"
http-outgoing-0 >> "Connection: Keep-Alive[\r][\n]"
http-outgoing-0 >> "User-Agent: Apache-HttpClient/4.5.5 (Java/1.8.0_172)[\r][\n]"
http-outgoing-0 >> "Authorization: Basic xxxxxxxxxxxxxxx[\r][\n]"
http-outgoing-0 >> "[\r][\n]"
http-outgoing-0 << "HTTP/1.1 403 Forbidden[\r][\n]"

使用调试器,我一直到以下行:https://github.com/apache/httpcomponents-client/blob/6f4550ff977a8f497822a17115572dcdb6e715b6/httpclient/src/main/java/org/apache/http/impl/execchain/MainClientExec.java#L272

在这个循环中,请求第一次被执行。然后,在第 293 行,“needsAuthentication()”方法返回 true,请求再次执行。但我没有看到,第一个响应中的 cookie 应该复制到第二个请求的哪里。

【问题讨论】:

    标签: java apache-httpclient-4.x


    【解决方案1】:

    在查看MainClientExec.java(见上文)后,我认为这是一个错误或根本不支持的功能:Apache HttpClient 不会在“401”重试中设置 cookie。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-28
      • 2016-01-04
      • 2023-04-08
      • 1970-01-01
      • 1970-01-01
      • 2015-03-25
      • 1970-01-01
      • 2019-10-28
      相关资源
      最近更新 更多