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();
    ClientPNames.HANDLE_REDIRECTS, false);
  HttpPost httpPost = new HttpPost("http://localhost:8888/_ah/login");
  String email = URLEncoder.encode(username, "UTF-8");
    new StringEntity(
      "email=" + email + 
      "&continue=" + redirectUrl + 
  HttpResponse response = httpClient.execute(httpPost);
  String authenticationCookie 
   = response.getFirstHeader("Set-Cookie").getValue();
  return authenticationCookie;

 public static void main(String[] args) throws Exception {
  AppEngineLocalhostClient client = new AppEngineLocalhostClient();
  String username="";
  boolean iWantToBeAdmin = true;
  String afterLoginGetMeToThisUrl 
   = URLEncoder.encode("http://localhost:8888", "UTF-8");
  String authenticationCookie = client.authenticateAtLocalhost(
  // ... 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 MindForger. It took me a bit of time to determine how exactly to do that - lets save it for you.

Labels: , , , , ,