Jul 22, 2010

Adding cookies to your Hessian requests

Many authentication schemes use cookies in Http requests to accomplish their task. For example, if you want to implement Google Account authentication in your Android app that uses GAE as the backend you need a way to embed cookies in your request. The Hessian reference implementation does not provide a way to handle cookies out of the box. The hessdroid implementation has some support for cookies but I haven't used it.

Adding basic cookie support is fairly straightforward. All we need to do is extend the HessianProxy class like we did in the previous post with MyHessianProxy.

class CookieProxy extends HessianProxy {
  protected final ICookieProvider cookieProvider;

  CookieProxy(
      HessianProxyFactory factory,
      URL url,
      ICookieProvider cp) {
    super(url, factory);
    cookieProvider = cp; 
  }

  @Override
  protected void addRequestHeaders(HessianConnection conn) {
    super.addRequestHeaders(conn);
    if (cookieProvider != null && 
        cookieProvider.getCookie() != null) {
      conn.addHeader("Cookie", cookieProvider.getCookie());
    }
    conn.addHeader("Content-Type", "x-application/hessian");
  }
}

The constructor receives a ICookieProvider interface aside from the factory and url parameters which are simply forwarded to the parent constructor. The ICookieProvider interface is very simple:

interface ICookieProvider {
    String getCookie();
}

Its getCookie method is used to retrieve the cookie content from the provider that implements it. The main point of interest here is the HessianProxy-s addRequestHeader method which was overridden in order to add our custom Cookie header. The content type header is also set in this method. That's all there is to it. By using this proxy we can send any kind of cookie in the Http requests that are sent to the server when a method is invoked on the proxy.
The last step is to add a new factory method to the defined in the previous post that will use this proxy.

public enum ProxyFactory {;
    ...
    public static T getCookieProxy(
        Class proxyClass,
        String relativePath,
        ICookieProvider cp) {
      URL url;
      try {
        url = new URL("http://" + defaultServerUrl + "/" +               relativePath);
      } catch (MalformedURLException e) {
        throw new RuntimeException(e);
      }
      HessianProxy proxy = new CookieProxy(factory, url, cp);
      T o = (T) Proxy.newProxyInstance(
          classLoader,
          new Class[]{proxyClass, HessianRemoteObject.class},
          proxy);
     return o;
  }
}


Now we can use this method to generate a proxy that sends cookies to the server from anywhere in our code.

No comments:

Post a Comment