You are viewing a plain text version of this content. The canonical link for it is here.
Posted to httpclient-users@hc.apache.org by Franck Borel <bo...@ub.uni-freiburg.de> on 2006/10/17 10:37:02 UTC

HttpClient and Form Authentication

Hi,

I would like to use the HttpClient API to fill in automaticaly an 
authentication request of my Tomcat form authentication.
In a first step I send a GET request to get the JSESSIONID. A second 
step I send username, password and the cookie  calling the j_security to 
passing through the authentication.

But I get only the login-error.jsp message back. I think this have to do 
with my cookie. Can anybody help me?

Here is the code I am using:

================================================================== BEGIN
package de.vascoda.aar.shibboleth.idp;

import java.io.IOException;

import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpState;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;

public class ClientAutoAuthentication {
	
	public static void main(String[] args) throws HttpException, IOException {
		
		// Set target URL
     	String strURL = 
"http://localhost:8080/shibboleth-idp-krz/SSO-guest";
         System.out.println("Target URL: " + strURL);

         // Get initial state object
         HttpState initialState = new HttpState();

         // Initial set of cookies can be retrieved from persistent storage
         // and re-created, using a persistence mechanism of choice,
         //Cookie mycookie = new Cookie(".foobar.com", "mycookie", "stuff",
         //        "/", null, false);

         // and then added to your HTTP state instance
         //initialState.addCookie(mycookie);

         // Get HTTP client instance
         HttpClient httpclient = new HttpClient();
         httpclient.getHttpConnectionManager().
                 getParams().setConnectionTimeout(30000);
         httpclient.setState(initialState);

         // RFC 2101 cookie management spec is used per default
         // to parse, validate, format & match cookies
         //httpclient.getParams().setCookiePolicy(CookiePolicy.RFC_2109);

         // A different cookie management spec can be selected
         // when desired

         //httpclient.getParams().setCookiePolicy(CookiePolicy.NETSCAPE);
         // Netscape Cookie Draft spec is provided for completeness
         // You would hardly want to use this spec in real life situations
 
httpclient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
         // Compatibility policy is provided in order to mimic cookie
         // management of popular web browsers that is in some areas
         // not 100% standards compliant

         // Get HTTP GET method
         GetMethod httpget = new GetMethod(strURL);

         // Execute HTTP GET
         int result = httpclient.executeMethod(httpget);

         // Display status code
         System.out.println("Response status code: " + result);

         // Get all the cookies
         Cookie[] cookies = httpclient.getState().getCookies();

         // Display the cookies
         System.out.println("Present cookies: ");
         for (int i = 0; i < cookies.length; i++) {
             System.out.println(" - " + cookies[i].toExternalForm());
         }

         // Release current connection to the connection pool
         // once you are done
         httpget.releaseConnection();

         //Cookie ist da und Jetzt wird eingeloggt
		PostMethod postMethod = new 
PostMethod(("http://localhost:8080/shibboleth-idp-krz/SSO-guest/j_security_check")); 

		//postMethod.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
		NameValuePair[] postData = new NameValuePair[2];
		postData[0] = new NameValuePair("j_username", "demo");
		postData[1] = new NameValuePair("j_password", "demo");
		
		//postMethod.addParameters(postData);
		postMethod.setRequestBody(postData);
		for(int i = 0; i < cookies.length; i++){
			postMethod.setRequestHeader("Cookie:", cookies[i].toExternalForm());
		}
		
		try {
			httpclient.executeMethod(postMethod);
		
		} catch (HttpException httpe) {
			System.err.print("HttpException");
			System.err.println(httpe.getMessage());
			httpe.printStackTrace();
		} catch (IOException ioe) {
			System.err.print("IOException");
			System.err.println(ioe.getMessage());
			ioe.printStackTrace();
		}
		
		String responseBody = postMethod.getResponseBodyAsString();
		System.out.println(responseBody);
		
		postMethod.releaseConnection();
		
     }
}
=================================================================== END


This is the header of the normal way to authenticate via form 
authentication:

===================================================================BEGIN
http://localhost:8080/shibboleth-idp-krz/j_security_check

POST /shibboleth-idp-krz/j_security_check HTTP/1.1
Host: localhost:8080
User-Agent: Mozilla/5.0 (X11; U; Linux i686; de; rv:1.8.0.7) 
Gecko/20060921 Ubuntu/dapper-security Firefox/1.5.0.7
Accept: 
text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5
Accept-Language: de-de,de;q=0.8,en-us;q=0.5,en;q=0.3
Accept-Encoding: gzip,deflate
Accept-Charset: UTF-8,*
Keep-Alive: 300
Connection: keep-alive
Referer: http://localhost:8080/shibboleth-idp-krz/SSO-ub
Cookie: JSESSIONID=34AD3C1181259059BA4A1F215D61DF60
Content-Type: application/x-www-form-urlencoded
Content-Length: 57
j_username=demo03&j_password=demo&Login=Login
HTTP/1.x 302 Moved Temporarily
Server: Apache-Coyote/1.1
Location: http://localhost:8080/shibboleth-idp-krz/SSO-ub
Content-Length: 0
Date: Mon, 16 Oct 2006 07:47:04 GMT
================================================================== END

Thanks!

-- Franck


Re: HttpClient and Form Authentication

Posted by Roland Weber <RO...@de.ibm.com>.
Hi Franck,

> > Have you studied the Client HTTP Programming Primer?
> > http://wiki.apache.org/jakarta-httpclient/ForAbsoluteBeginners
> Thanks Roland
> 
> Yep. But this doesn't help me much. The tutorial doesn't desribe how to 
> automate the j_security_check - form-based authentication. There ready 
> to use schemas for BasicAuth, Digest and so on but no j_security-check 
> form-based authentication :-(.

Basic and Digest authentication are on the HTTP level. Form based
authentication is on the application level. The tutorial is all
about submitting forms, whether for authentication or not ;-)
Maybe I'll add a sentence or two about form based authentication
when I find the time.

> I found some code snipples in the net 
> 
(http://forum.java.sun.com/thread.jspa?threadID=546542&messageID=4154990) 
> and I have builded a program that does the thing that I need.

Glad you made it.

cheers,
  Roland



Re: HttpClient and Form Authentication

Posted by Franck Borel <bo...@ub.uni-freiburg.de>.
Hi Roland,

Thanks for your answer.

> Have you studied the Client HTTP Programming Primer?
> http://wiki.apache.org/jakarta-httpclient/ForAbsoluteBeginners
Thanks Roland

Yep. But this doesn't help me much. The tutorial doesn't desribe how to 
automate the j_security_check - form-based authentication. There ready 
to use schemas for BasicAuth, Digest and so on but no j_security-check 
form-based authentication :-(.
I found some code snipples in the net 
(http://forum.java.sun.com/thread.jspa?threadID=546542&messageID=4154990) 
and I have builded a program that does the thing that I need.

Here is the code that works:

------------------------------------------------------BEGIN
import java.io.IOException;

import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpState;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;


public class ClientAutoAuthentication {
	
	public static void main(String[] args) throws HttpException, IOException {
		

     	String strURL = "http://localhost:8080/test-form-auth/test.jsp";
         System.out.println("Target URL: " + strURL);


         HttpState initialState = new HttpState();

         HttpClient httpclient = new HttpClient();
 
httpclient.getHttpConnectionManager().getParams().setConnectionTimeout(30000);
         httpclient.setState(initialState);

         // RFC 2101 cookie management spec is used per default
         // to parse, validate, format & match cookies
         httpclient.getParams().setCookiePolicy(CookiePolicy.RFC_2109);


         GetMethod httpget = new GetMethod(strURL);

         int result = httpclient.executeMethod(httpget);

         System.out.println("Response status code: " + result);

         Cookie[] cookies = httpclient.getState().getCookies();

         System.out.println("Present cookies: ");
         for (int i = 0; i < cookies.length; i++) {
             System.out.println(" - " + cookies[i].toExternalForm());
         }

         httpget.releaseConnection();

	PostMethod postMethod = new 
PostMethod(("http://localhost:8080/test-form-auth/j_security_check")); 

		NameValuePair[] postData = new NameValuePair[3];
		postData[0] = new NameValuePair("j_username", "test");
		postData[1] = new NameValuePair("j_password", "test");
		postData[2] = new NameValuePair("Login", "login");
		
		postMethod.addParameters(postData);
		
		for(int i = 0; i < cookies.length; i++){
			initialState.addCookie(cookies[i]);
		}
		httpclient.setState(initialState);
		
		try {
			httpclient.executeMethod(postMethod);
		
		} catch (HttpException httpe) {
			System.err.print("HttpException");
			System.err.println(httpe.getMessage());
			httpe.printStackTrace();
		} catch (IOException ioe) {
			System.err.print("IOException");
			System.err.println(ioe.getMessage());
			ioe.printStackTrace();
		}
				
		postMethod.releaseConnection();
		
		GetMethod getMethod = new 
GetMethod("http://localhost:8080/test-form-auth/test.jsp");
		try {
			httpclient.executeMethod(getMethod);
		} catch (HttpException httpe) {
			System.out.println(httpe.getMessage());
		} catch (IOException ioe) {
			System.out.println(ioe.getMessage());
		}
		String responseBody = getMethod.getResponseBodyAsString();
		System.out.println(responseBody);
		
		getMethod.releaseConnection();
     }
}

-----------------------------------------------------------END

The only problem is that, I need to integrate this programm in a 
servlet. This is quite different and very frustrating :-(.

Have anybody an idey how to integrate this in a servlet context ?

-- Franck









Re: HttpClient and Form Authentication

Posted by Roland Weber <RO...@de.ibm.com>.
Hello Franck,

Franck Borel <bo...@ub.uni-freiburg.de> wrote on 17.10.2006 10:37:02:

> I would like to use the HttpClient API to fill in automaticaly an 
> authentication request of my Tomcat form authentication.
> In a first step I send a GET request to get the JSESSIONID. A second 
> step I send username, password and the cookie  calling the j_security to 

> passing through the authentication.
> 
> But I get only the login-error.jsp message back. I think this have to do 

> with my cookie. Can anybody help me?

Have you studied the Client HTTP Programming Primer?
http://wiki.apache.org/jakarta-httpclient/ForAbsoluteBeginners

cheers,
  Roland