Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

After upgrading to Apache HttpClient 4.4 it does not send cookies with requests

I am using the Apache HttpClient to send requests to our internal API servers. The servers require authentication and need a cookie to be set with an auth token.

Up to HttpClient 4.3.6 this has been working fine, but on 4.4 and above it has stopped sending the cookies on requests. My cookie domain is set to .subdomain.mycompany.com, which works for 4.3.6, but not 4.4 and above. If I'm more specific and give the full host as the cookie domain, i.e. host.subdomain.mycompany.com it works, but this is not a solution.

Here's a code snippet similar to what I'm doing:

public CloseableHttpResponse execute(CloseableHttpClient httpClient) throws IOException {
    BasicClientCookie cookie = new BasicClientCookie("cookieName", "myAuthtoken");
    cookie.setPath("/");
    cookie.setDomain(".subdomain.mycompany.com");
    cookie.setSecure(false);
    HttpContext localContext = new BasicHttpContext(parentContext);
    CookieStore cookieStore = new BasicCookieStore();
    cookieStore.addCookie(cookie);
    localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);
    return httpClient.execute(target, request, localContext);
}

The httpClient is already constructed and passed into this code which sets the auth cookie.

I saw this, which is similar Cookies getting ignored in Apache httpclient 4.4, but in my case the cookies aren't being sent to the server.

After turning on wire logging in the HttpClient I can see the following in 4.3.6, but not in 4.4 and above:

DEBUG [org.apache.http.client.protocol.RequestAddCookies] Cookie [version: 0][name: cookieName][value: authToken][domain: .subdomain.mycompany.com][path: /][expiry: Wed Jul 15 16:07:05 IST 2015] match [host.subdomain.mycompany.com:80/myApi]

Which leads me to think it's something to do with cookie domain matching. Anyone have any ideas? Thanks.

like image 478
Colin Kennedy Avatar asked Jul 14 '15 16:07

Colin Kennedy


1 Answers

I have debugged the example code. The problem is at BasicDomainHandler.match(Cookie, CookieOrigin) line: 129 as it expects org.apache.http.cookie.ClientCookie.DOMAIN_ATTR to be set in order to match full host name from URL to cookie domain. So you need to add the following line to your code, after you set the domain:

cookie.setAttribute(ClientCookie.DOMAIN_ATTR, "true");

The change was added with revision 1646864 on 12/19/14, 10:59 PM:

RFC 6265 compliant cookie spec

like image 191
Anton Krosnev Avatar answered Nov 01 '22 20:11

Anton Krosnev