yet another blog about computer, technology, programming, and internet

Monday, May 02, 2011

Using ClientLogin to do Authentication for App Engine Application

Monday, May 02, 2011 Posted by Ismail Habib , 38 comments
General information about ClientLogin:

Discussion on Google Groups (including the original solution posted by geoffd123):

My solution uses Apache Http library instead of HttpUnit.
public static String loginToGoogle(String userid, String password,
   String appUrl) throws Exception {
  HttpClient client = new DefaultHttpClient();
  HttpPost post = new HttpPost(
  MultipartEntity reqEntity = new MultipartEntity();
  reqEntity.addPart("accountType", new StringBody("HOSTED_OR_GOOGLE",
    "text/plain", Charset.forName("UTF-8")));
  reqEntity.addPart("Email", new StringBody(userid));
  reqEntity.addPart("Passwd", new StringBody(password));
  reqEntity.addPart("service", new StringBody("ah"));
  reqEntity.addPart("source", new StringBody(
  HttpResponse response = client.execute(post);
  if (response.getStatusLine().getStatusCode() == 200) {
   InputStream input = response.getEntity().getContent();
   String result = IOUtils.toString(input);
   String authToken = getAuthToken(result);
   post = new HttpPost(appUrl + "/_ah/login?auth=" + authToken);
   response = client.execute(post);
   Header[] cookies = response.getHeaders("SET-COOKIE");
   for (Header cookie : cookies) {
    if (cookie.getValue().startsWith("ACSID=")) {
     return cookie.getValue();
   throw new Exception("ACSID cookie cannot be found");
  } else
   throw new Exception("Error obtaining ACSID");
A simple example on how to use it:

String authCookie = logonHelper.loginToGoogle("",
DefaultHttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet("");
get.setHeader("Cookie", authCookie);
HttpResponse response = client.execute(get);