Tuesday, May 28, 2013

Google OAuth on Android using AccountManager

Implementing a proper OAuth flow on Android is a lot more complicated than it should be. Either you use a custom WebView (sucks for the user, because it doesn't autocomplete his usernames and passwords) or register your app for a certain URL-scheme ("myoauthcallback://..."), which is a really strange (and hijackable!) solution.

The solution is Android's AccountManager! At least if you're trying to authorize to a Google service which supports OAuth (most of them do, thankfully). I think Twitter supports the AccountManager too, but that's semi-official I guess...

Anyway, here's a really simple implementation of an activity which 1. asks the user for the Google account to use for authentication and 2. requests a token for that account. It handles some of the common gotchas during the authentication / authorization "dance", but it doesn't handle things like missing connectivity, etc.

PS: If you want to request multiple scopes, provide them as a space-separated list, like this: "oauth2:https://www.googleapis.com/auth/glass.timeline https://www.googleapis.com/auth/userinfo.profile"

If you want to read more about the AccountManager, check out the official docs here.

No comments:

Post a Comment