I have a Java app (jetty server) built with Spring (MVC, security, transactions, etc) and uses REST for webservices. I have another Java client that makes REST calls to the server using Apache HTTPClient (HttpComponents). The server app uses form-based authentication and web client uses j_spring_security_check form to login to the app. So, from Java client I use [https://host:port/myapp/j_spring_security_check?j_username=myuser&j_password=mypass] using POST to do the login. Authentication is working fine (it reaches the UserDetailService's child class and successfully does authentication), but subsequent REST calls fail indicating as if user was not authenticated (the call doesn't even reach the controller method for the given rest call). I get back one of the app's html page (this is one of the jsp pages).
I am printing Cookies for every request (including login) and it prints different jsessionid for each request (request is the rest call to the server). Here are the cookies, one for each request, first request is the login request (see that jsessionid is different for each request):
cookies: [[version: 0][name: JSESSIONID][value: 1x5i3b0lbf5o7xv52kjh0vu89][domain: 127.0.0.1][path: /webui][expiry: null]]
cookies: [[version: 0][name: JSESSIONID][value: t05vbrffqv6t1xcygps9l6jaz][domain: 127.0.0.1][path: /webui][expiry: null]]
cookies: [[version: 0][name: JSESSIONID][value: 8v5i5ofbgr201kh2txxale674][domain: 127.0.0.1][path: /webui][expiry: null]]
is different jsessionid for each request the problem/cause? How do I get around this problem? Here is the code with HttpClient:
request = new HttpPost(url);
httpClient = new DefaultHttpClient();
httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", 443, socketFactory));
HttpResponse response = httpClient.execute(request);
System.out.println("cookies: " + httpClient.getCookieStore().getCookies());
HttpEntity resp_ent = response.getEntity();
this.status_code = response.getStatusLine().getStatusCode();
Do we need to do anything special to store the cookies? Any help is very much appreciated.
It's not obvious from the code snippet you showed, so I'm not sure if this is the problem, but make sure you don't create a new DefaultHttpClient() for each request, otherwise the new client will have a new CookieStore.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With