I like how easy Google Cloud Endpoints makes it to create a REST API on Google App Engine. Granted, there are other solutions in the Java world (I also used RestX and Spring) but I still like the simplicity of Google Cloud Endpoints.
However, one problem with Cloud Endpoints is the authentication : by default it only supports Google’s OAuth2 authentication protocol. Because my application uses sessions for other purposes, I wanted to authenticate the user based on his session. Endpoints authentication is actually extensible through an almost undocumented class called Authenticator.
Another issue is that this authenticator does not have access to the session either… The Endpoints infrastructure strips off the cookies and session information before injecting the HttpServletRequest in Authenticator.authenticate().
The solution I found is to send the session id in a header. In App Engine, sessions are stored in memcache and the datastore, so I can extract those sessions easily. Here’s how it works :
In this code, the Authenticator gets the session id from the X-MYAPP-JSESSIONID HTTP header. It then tries to fetch and deserialize the session info from memcache. If this fails, the session is retrieved from the datastore.
Important : this only works correctly if you invalidate the session when the user logs out and then logs back in. If one given session can be associated with more than one MyAppUser, or if the MyAppUser object changes during the session’s life (for example if you update attributes) then the SessionDataInMemcache object will be out of sync. This was not a problem for my application.
Then all I need to do is configure jQuery to include the session ID as a header when it makes AJAX calls, here’s how it’s done :
The Cookies class here is provided by a small Cookies.js library.
All we have to do now is to configure our Cloud Endpoints API. Note the authenticators parameter on the @Api annotation.
That’s it ! We are now ready to roll with a Google Cloud Endpoints service protected by Java’s standard HTTP sessions.