Created
September 3, 2012 14:22
-
-
Save Mononofu/3609672 to your computer and use it in GitHub Desktop.
Use OAuth 2 with App Engine by requesting a cookie
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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