Monday, May 02, 2011

Using ClientLogin to do Authentication for App Engine Application

General information about ClientLogin: http://code.google.com/apis/accounts/docs/AuthForInstalledApps.html

Discussion on Google Groups (including the original solution posted by geoffd123):
http://groups.google.com/group/google-appengine-java/browse_thread/thread/c96d4fff73117e1d

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(
    "https://www.google.com/accounts/ClientLogin");
  
  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(
    "YourCompany-YourApp-YourVersion"));
  post.setEntity(reqEntity);
  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("email@gmail.com",
   "password","http://yourapp.appspot.com");  
DefaultHttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet("http://yourapp.appspot.com/service");
get.setHeader("Cookie", authCookie);
HttpResponse response = client.execute(get);
response.getEntity().writeTo(System.out);

5 comments:

  1. thanks codenya bos, salam kenal

    ReplyDelete
  2. Hi,
    this code is very helpful for me.. now i can easily do authentication.. thanks for sharing this information

    ReplyDelete
  3. helpful blog, thanks for sharing.

    Michael

    ReplyDelete
  4. Thanks very much. I referenced this in http://stackoverflow.com/questions/9078003/accessing-oauth-protected-resource-on-google-app-engine/9405067#9405067

    ReplyDelete
    Replies
    1. glad that you found it useful!

      Delete