Skip to content

Instantly share code, notes, and snippets.

@Mononofu
Created September 3, 2012 14:22
Show Gist options
  • Save Mononofu/3609672 to your computer and use it in GitHub Desktop.
Save Mononofu/3609672 to your computer and use it in GitHub Desktop.
Use OAuth 2 with App Engine by requesting a cookie
// this is kind of a hack since App Engine doesn't support OAuth 2, but that's the
// only version of OAuth that's natively supported by Android
val token = settings.getString("oauth2_token", "")
// send OAuth token to appspot login page
// response will contain a valid cookie
val req = new HttpGet("https://x-allow-oauth-dot-google-showy.appspot.com/_ah/login?continue=http://localhost/&auth=" + token);
val client = new DefaultHttpClient()
// avoid redirects - we are only interested in the cookie, not any content
client.getParams.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, false)
// we are not interested in the result, so no need to save it
client.execute(req);
import scala.collection.JavaConversions._
val cookies = client.getCookieStore().getCookies()
// if the response contains the right cookie, then we successfully authenticated
if(cookies.exists(_.getName() == "SACSID")) {
// enable redirects again to make the request we initially wanted
// we are reusing the same HttpClient, so the cookie is still set
client.getParams.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, true)
val req = new HttpGet(url)
req.setHeader("X-Same-Domain", "true")
val resRaw = client.execute(req)
val res = (resRaw.getStatusLine().getStatusCode(), io.Source.fromInputStream(resRaw.getEntity().getContent()).mkString(""))
log("Response Status Code: " + res._1);
log("Response body:" + res._2);
} else {
// otherwise, something was wrong with our OAuth token - maybe it expired?
runOnUiThread { showPopup("Authentication failed") }
(500, "auth failed")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment