Saturday, December 03, 2011

Google App Engine SDK: HttpClient authentication on localhost

public class AppEngineLocalhostClient {

 public String authenticateAtLocalhost(
     String username, 
     boolean asAdmin, 
     String redirectUrl) throws Exception {
  HttpClient httpClient = new DefaultHttpClient();
  httpClient.getParams().setBooleanParameter(
    ClientPNames.HANDLE_REDIRECTS, false);
  
  HttpPost httpPost = new HttpPost("http://localhost:8888/_ah/login");
  httpPost.setHeader("Content-Type","application/x-www-form-urlencoded");
  String email = URLEncoder.encode(username, "UTF-8");
  httpPost.setEntity(
    new StringEntity(
      "email=" + email + 
      "&continue=" + redirectUrl + 
      (asAdmin?"&isAdmin=on":"")));
  HttpResponse response = httpClient.execute(httpPost);
  
  String authenticationCookie 
   = response.getFirstHeader("Set-Cookie").getValue();
  httpClient.getConnectionManager().shutdown();
  
  return authenticationCookie;
 }

 public static void main(String[] args) throws Exception {
  AppEngineLocalhostClient client = new AppEngineLocalhostClient();
  
  String username="test@example.com";
  boolean iWantToBeAdmin = true;
  String afterLoginGetMeToThisUrl 
   = URLEncoder.encode("http://localhost:8888", "UTF-8");
  String authenticationCookie = client.authenticateAtLocalhost(
    username,
    iWantToBeAdmin, 
    afterLoginGetMeToThisUrl);
  
  // ... access the REST interface authenticated
  
  HttpGet httpget = new HttpGet("http://localhost:8888/rest");
  httpget.addHeader("Cookie", authenticationCookie);
  
  // ...  
 }
}
When developing a Google App Engine application using SDK on localhost you sometimes need to authenticate programatically. For example in case that your application has a REST-style interface like CoachingNotebook. It took me a bit of time to determine how exactly to do that - lets save it for you.

Labels: , , , , ,