Droidcedas : Unmarried Sign-On To Google Sites Using Accountmanager

In the recent example with total source code. This integration complexity together with UI impedance mismatch are the problems that OAuth 2.0 support via the AccountManager initially, together with recently first part of this series, nosotros presented how the criterion Android online line of piece of work organisation human relationship administration framework plant together with explored how Google line of piece of work organisation human relationship authentication together with potency modules are implemented on Android. In this article nosotros volition run into how to utilization the Google credentials stored on the device to log inwards to Google Web sites automatically. Note that this is different from using world Google API's, which to a greater extent than frequently than non only requires putting an authentication token (and perchance an API key) inwards a asking header, together with is quite good supported past times the Google APIs Client Library. First, some words on what motivated this whole practice (may include some ranting, experience gratis to skip to the side past times side section).

Android developer console API: DIY

If yous remove hold ever published an application on the Android Market Google Play Store, yous are familiar alongside the Android developer console. Besides letting yous divulge together with update your apps, it also shows the number of total together with active installs (notoriously broken together with non too live taken too seriously, though it's been getting ameliorate lately), ratings together with comments. Depending on how excited virtually the whole app publishing line of piece of work organisation yous are, yous mightiness desire to cheque it quite frequently to run into how your app is doing, or maybe yous just similar hitting F5. Most people don't however, thus pretty much every developer at some betoken comes upwards alongside the heretic thought that at that topographic point must live a ameliorate way: yous should live able to cheque your app's statistics on your Android device (obviously!), yous should instruct notified virtually changes automatically together with maybe fifty-fifty live able to easily run into if today's numbers are ameliorate than yesterday's at a glance. Writing such a tool should live fairly easy, thus yous start looking for an API. If your search ends upwards empty it's non your search engine's fault: at that topographic point is none! So before yous start scraping those pretty Web pages alongside your favourite P-language, yous cheque if someone has done this before -- yous mightiness instruct a few hits, together with if yous are lucky fifty-fifty discover the Android app.

Originally developed past times Timelappse, together with right away open source, Andlytics does all the things mentioned above, together with to a greater extent than (and if yous demand yet some other feature, consider contributing). So how does it deal to produce all of this without an API? Through blood, elbow grease together with a lot of protocol reversing guessing. You see, the electrical current developer console is built on GWT which used to live Google's webstack-du-jour a few years back. GWT essentially consists of RPC endpoints at the server, called past times a JavaScript customer running inwards the browser. The serialization protocol inwards betwixt is a custom one, together with the specification is purposefully non publicly available (apparently, to allow for easier changes!?!). It has 2 primary features: yous demand to know precisely how the transferred objects facial expression similar to live able to brand whatever feel of it, together with it was patently designed past times someone who used to write compilers for a living before they got into Web evolution ('string table' band a bell?). Given the above, Andlytics was quite an accomplishment. Additionally, the developer console changing its protocol every other calendar week together with adding novel features from fourth dimension to fourth dimension didn't genuinely arrive whatever easier to maintain. Eventually, the original developer had a fleck too much GWT on his plate, together with was form plenty to opened upwards source it, thus others could part the pain.

But at that topographic point is a brilliant side to all this: recent example with total source code. This integration complexity together with UI impedance mismatch are the problems that OAuth 2.0 support via the AccountManager initially, together with recently Developer Console v2. It was announced at this year's Google I/O to much applause, but was only made universally available a duet of weeks agone (sound recent example with total source code. This integration complexity together with UI impedance mismatch are the problems that OAuth 2.0 support via the AccountManager initially, together with recently familiar?). It is a operate inwards progress, but is showing promise. And the best part: it uses perfectly readable (if a fleck heavy on null's) JSON to carry data! Naturally, at that topographic point was much rejoicing at the Andlytics Github project. It was unanimously decided that the sooner nosotros obliterate all traces of GWT, the better, together with the side past times side version should utilization the v2 console 'API'. Deciphering the protocol didn't remove hold long, but it turned out that piece to log inwards to the v1 console all yous needed was a ClientLogin (see the side past times side department for an explanation) token straight out of Android's AccountManger, the novel ane was non thus forgiving together with the login catamenia was somewhat more complex. Asking the user for their password together with using it to login was patently doable, but no ane would similar that, thus nosotros needed to figure out how to log inwards using the Google credentials already cached on the device. Android browser together with Chrome are able to automatically log yous inwards to the developer console without requiring your password, thus it was clearly possible. The procedure is non genuinely documented though, together with that prompted this (maybe a fleck too wide-cast) investigation. Which finally leads us to the theme of this post: to exhibit how to utilization cached Google line of piece of work organisation human relationship credentials for unmarried sign-on. Let's initiatory of all run into what criterion ways are available to authenticate to Google's world services together with API's.

Google services authentication together with authorization

The official house to start when selecting an auth machinery is the Google Accounts Authentication together with Authorization page. It lists quite a few protocols, some opened upwards together with some proprietary. If yous enquiry farther yous volition discover that currently all but OAuth 2.0 together with Open ID are considered deprecated, together with using the proprietary ones is non recommended. However, a lot of services are still using older, proprietary protocols, thus nosotros volition facial expression into some of those every bit well. Most protocols also remove hold 2 variations: ane for Web applications together with ane for the thus called, 'installed applications'. Web applications run inwards a browser, together with are expected to live able to remove hold payoff of all criterion browser features: rich UI, free-form user interaction, cookie shop together with powerfulness to follow redirects. Installed applications, on the other hand, don't remove hold a native way to preserve session information, together with may non remove hold the total Web capabilities of a browser. Android native applications (mostly) autumn inwards the 'installed applications' category, thus let's run into what protocols are available for them.

ClientLogin

The oldest together with most widely used till right away potency protocol for installed applications is recent example with total source code. This integration complexity together with UI impedance mismatch are the problems that OAuth 2.0 support via the AccountManager initially, together with recently previous post, inwards Android this is handled past times GLS together with the associated online service past times storing an encrypted password or a original token on the device. Getting a token is every bit uncomplicated every bit calling the appropriate AccountManger method, which either returns a cached token or issues an API asking to fetch a fresh one. Despite it's many limitations, the protocol is piece of cake to sympathise together with straightforward to implement, thus it has been widely used. It has been recent example with total source code. This integration complexity together with UI impedance mismatch are the problems that OAuth 2.0 support via the AccountManager initially, together with recently officially deprecated since Apr 2012 though, together with apps using it are encouraged to migrate to OAuth 2.0, but this hasn't quite happened yet. 

OAuth 2.0

No ane likes OAuth 1.0 (except Twitter) together with AuthSub is non quite suited for native applications, thus nosotros volition only facial expression at the currently recommended OAuth 2.0 protocol. OAuth 2.0 has been inwards the plant for quite some time, but it only late became an official Internet standard. It defines different potency 'flows', aimed at different utilization cases, but nosotros volition non attempt to acquaint all of them here. If yous are unfamiliar alongside the protocol, refer to ane of the multiple posts that aim to explicate it at a higher level, or just read the RFC if yous demand the details.  And, of course, yous tin give the axe sentry for this for a slightly different betoken of view. We volition only verbalize over how OAuth 2.0 relates to native mobile applications.

The OAuth 2.0 specification defines four basic flows for getting an potency token for a resource, together with the 2 ones that don't require the customer (in our scenario an Android app) to straight handgrip user credentials (Google line of piece of work organisation human relationship user call together with password), namely the authorization code grant flow together with the implicit grant flow, both remove hold a mutual footstep that needs user interaction. They both require the potency server (Google's) to authenticate the resources possessor (the user of the our Android app) together with constitute whether they grant or deny the access asking for the specified range (e.g., read-only access to profile information). In a typical Web application that runs inwards a browser, this is rattling straightforward to do: the user is redirected to an authentication page, thus to a access grant page that basically says 'Do yous allow app X to access information Y together with Z?', together with if they agree, some other redirect, which includes an potency token, takes them dorsum to the original application. The browser only needs to exceed on the token inwards the side past times side asking to gain access to the target resource. Here's an official Google instance that uses the implicit flow: follow this link together with grant access every bit requested to permit the demo Web app display your Google profile information. With a native app things are non that simple. It tin give the axe either
  • use the arrangement browser to handgrip the permission grant step, which would typically involve the next steps:
    • launch the arrangement browser together with hope that the user volition destination the authentication together with permission grant process
    • detect success or failure together with extract the potency token from the browser on success (from the window title, redirect URL or the cookie store)
    • ensure that after granting access, the user ends upwards dorsum inwards your app
    • finally, salve the token locally together with utilization it to number the intended Web API request
  • embed a WebView or a similar command inwards the apps's UI. Getting a token would to a greater extent than frequently than non involve these steps:
    • in the app's UI, instruct the user what to produce together with charge the login/authorization page
    • register for a 'page loaded' callback, together with cheque for the concluding success URL each fourth dimension it's called
    • when found, extract the token from the redirect URL or the WebView's cookie jolt together with salve it locally
    • finally utilization the token to ship the intended API request
Neither is ideal, both are confusing to the user together with to implement the initiatory of all ane on Android yous mightiness lawsuit remove hold to (temporarily) start a Web server (redirect_uri is laid to https://androidcerdas.blogspot.com//search?q=06/oauth-2-0-flow-android/">recent example with total source code. This integration complexity together with UI impedance mismatch are the problems that OAuth 2.0 support via the AccountManager initially, together with recently Google Play Services aim to solve. When using either of those, user authentication is implemented transparently by passing the saved original token (or encrypted password) to the server side component, together with instead of a WebView alongside a permission grant page, yous instruct the Android native access grant dialog. If yous approve, a instant asking is sent to remove this together with the returned access token is straight delivered to the requesting app. This is essentially the same catamenia every bit for Web applications, but has the advantages that it doesn't require context switching from native to browser together with back, together with is much to a greater extent than user friendly. Of course, it only plant for Google accounts, thus if yous wanted to write, say, a Facebook client, yous still remove hold to utilization a WebView to procedure the access permission grant together with instruct an potency token.

Now that nosotros remove hold an thought what authentication methods are available, let's run into if nosotros tin give the axe utilization them to access an online Google service that doesn't remove hold a dedicated API.

Google Web properties unmarried sign-on

Being able to access multiple related, but carve upwards services without needing to authenticate to each ane individually is to a greater extent than frequently than non referred to every bit unmarried sign-on (SSO). There are multiple criterion ways to hit this for different contexts, ranging from Kerberos to SAML-based solutions. We volition utilization the term hither inwards a narrower meaning: existence able to utilization different Google services (Web sites or API's) after having authenticated to only ane of them (including the Android login service). If yous remove hold a fairly fast Internet connection, yous mightiness non fifty-fifty notice it, but after yous log inwards to, say, Gmail, clicking on YouTube links volition remove hold yous to a completely different domain, together with yet yous volition live able to comment on that bang-up truthful cat video without having to log inwards again. If yous remove hold a somewhat slower connexion together with a broad display though, yous may notice that at that topographic point is a lot of redirecting together with long parameter passing, alongside the occasional progress bar going on. What happens behind the scenes is that your electrical current session cookies together with authentication tokens are existence exchanged for yet other tokens together with to a greater extent than cookies, to permit yous seamlessly log inwards to that other site. If yous are curious, yous tin give the axe honour the catamenia alongside Chrome's built-in developer tools (or similar plugins for other browsers), or cheque out our sample. All of those requests together with responses are essentially a proprietary SSO protocol (Google's), which is non genuinely publicly documented anywhere, and, of course, is probable to modify fairly frequently every bit Google rolls out upgrades to their services. With that said, at that topographic point is a distinct pattern, together with on a higher aeroplane yous only remove hold 2 primary cases. We are deliberately ignoring the persistent cookie ('Stay signed in')  scenario for simplicity's sake.
  • Case 1: yous haven't authenticated to whatever of the Google properties. If yous access, for example, mail.google.com inwards that solid soil yous volition instruct a login covert originating at https://accounts.google.com/ServiceLogin alongside parameters specifying the service yous are trying to access ('mail' for Gmail) together with where to ship yous after yous are authenticated. After yous come inwards your credentials, yous volition to a greater extent than frequently than non instruct redirected a few times around the accounts.google.com, which volition laid a few session cookies, mutual (Domain=.google.com) for all services (always SID together with LSID, plus a few more). The lastly redirect volition live to the originally requested service together with include an authentication token inwards the redirected place (usually specified alongside the auth parameter, e.g.: https://mail.google.com/mail/?auth=DQAAA...). The target service volition validate the token together with laid a few to a greater extent than service-specific sessions cookies, restricted past times domain together with path, together with alongside the Secure together with HttpOnly flags set. From there, it mightiness remove hold a duet of to a greater extent than redirects before yous finally solid soil at an actual content page.
  • Case 2: yous remove hold already authenticated to at to the lowest degree ane service (Gmail inwards our example). In this state, if yous open, say, Calendar, yous volition instruct out through https://accounts.google.com/ServiceLogin again, but this fourth dimension the login covert won't live shown. The accounts service volition modify your SID together with LSID cookies, maybe laid a few novel ones together with finally redirect yous the original service, adding an authentication token to the redirect location. From at that topographic point the procedure is similar: ane or to a greater extent than service-specific cookies volition live laid together with yous volition finally live redirected to the target content.
Those flows patently operate good for browser-based logins, but since nosotros are trying to produce this from an Android app, without requiring user credentials or showing WebView's, nosotros remove hold a different scenario. We tin give the axe easily instruct a ClientLogin or an OAuth 2.0 token from the AccountManager, but since nosotros are non preforming an actual Web login, nosotros remove hold no cookies to present. The query becomes: is at that topographic point a way to log inwards alongside a criterion token alone? Since tokens tin give the axe live used alongside the information APIs (where available) of each service, they patently incorporate plenty information to authenticate us together with grant access to the service's resources. What nosotros demand is an Web endpoint, that volition remove hold our token together with give us a laid of cookies nosotros could utilization to access the corresponding Web site inwards exchange. Clues together with traces of such a service are scattered around the Internet, mostly inwards the code of unofficial Google customer libraries together with applications. Once nosotros know it is definitely possible, the side past times side work becomes getting it to operate alongside Android's AccountManger.

Logging inwards using AccountManager

The only existent documentation we could find, too code comments together with READMEs of the unofficial Google customer applications mentioned above, is a brusk Chromium OS design document. It tells us that the criterion (at the time) login API for installed applications, ClientLogin, lone is non plenty to hit Web SSO, together with outlines a 3 footstep procedure that lets us substitution ClientLogin tokens for session cookies valid for a exceptional service:
  1. Get a ClientLogin token (this nosotros tin give the axe produce via the AccountManager)
  2. Pass it to https://www.google.com/accounts/IssueAuthToken, to instruct a one-time use, short-lived token that volition authenticate the user to whatever service (the thus called, 'ubertoken')
  3. Finally, exceed the ubertoken to https://www.google.com/accounts/TokenAuth, to substitution it for the total laid of browser cookies nosotros demand to produce SSO
This outlines the process, but is a trivial low-cal on the details. Fortunately, those tin give the axe live found inwards the Chromium OS source code, every bit good every bit a few other projects. After a fair fleck of digging, here's what nosotros uncovered:
    1. To instruct the mythical ubertoken, yous demand to exceed the SID together with LSID cookies to the IssueAuthToken endpoint similar this:
      https://www.google.com/accounts/IssueAuthToken?service=gaia&Session=false&SID=sid&LSID=lsid 
    2. The reply volition give yous the ubertoken, which yous exceed to the TokenAuth endpoint along alongside the URL of the service yous desire to use:
      https://www.google.com/accounts/TokenAuth?source=myapp&auth=ubertoken&continue=service-URL 
    3. If the token cheque out OK, the reply volition give yous a URL to load. If your HTTP customer is gear upwards to follow redirects automatically, ane time yous charge it, needed cookies volition live laid automatically (just every bit inwards a browser), together with yous volition finally solid soil on the target site. As long every bit yous hold the same session (which commonly way the same HTTP customer instance) yous volition live able to number multiple requests, without needing to instruct out through the authentication catamenia again.
    What remains to live seen is, tin give the axe nosotros implement this on Android. As usual, it turns out that at that topographic point is to a greater extent than than ane way to produce it:

    The difficult way

    The straightforward way would live to only implement the catamenia outlined higher upwards using your favourite HTTP customer library. We pick out to utilization Apache HttpClient, which supports session cookies together with multiple requests using a unmarried instance out of the box. The initiatory of all footstep calls for the SID together with LSID cookies though, non an authentication token: nosotros demand cookies to instruct a token, inwards fellowship to instruct to a greater extent than cookies. Since Android's AccountManager tin give the axe only give us authentication tokens, together with non cookies, this mightiness seem similar a hopeless catch-22 situation. However, piece browsing the authtokens tabular array of the system's accounts database recent example with total source code. This integration complexity together with UI impedance mismatch are the problems that OAuth 2.0 support via the AccountManager initially, together with recently earlier, nosotros happened to notice that it genuinely had a bunch of tokens alongside type SID together with LSID. Our side past times side footstep is, of course, to attempt to asking those tokens via the AccountManager interface, together with this happens to operate every bit expected:

    String sid = am.getAuthToken(account, "SID", null, activity, null, null)     .getResult().getString(AccountManager.KEY_AUTHTOKEN); String lsid = am.getAuthToken(account, "LSID", null, activity, null, null)     .getResult().getString(AccountManager.KEY_AUTHTOKEN); 

    Having gotten those, the balance is just a affair of issuing 2 HTTP requests (error treatment omitted for brevity):

    String TARGET_URL = "https://play.google.com/apps/publish/v2/"; Uri ISSUE_AUTH_TOKEN_URL =   Uri.parse("https://www.google.com/accounts/IssueAuthToken?service=gaia&Session=false"); Uri TOKEN_AUTH_URL = Uri.parse("https://www.google.com/accounts/TokenAuth");  String url = ISSUE_AUTH_TOKEN_URL.buildUpon().appendQueryParameter("SID", sid)      .appendQueryParameter("LSID", lsid)      .build().toString(); HttpPost getUberToken = novel HttpPost(url); HttpResponse reply = httpClient.execute(getUberToken); String uberToken = EntityUtils.toString(entity, "UTF-8"); String getCookiesUrl = TOKEN_AUTH_URL.buildUpon()      .appendQueryParameter("source", "android-browser")      .appendQueryParameter("auth", authToken)      .appendQueryParameter("continue", TARGET_URL)      .build().toString(); HttpGet getCookies = novel HttpGet(getCookiesUrl); reply = httpClient.execute(getCookies);  CookieStore cookieStore = httpClient.getCookieStore(); // cheque for service-specific session cookie String adCookie = findCookie(cookieStore.getCookies(), "AD"); // neglect if non found, otherwise instruct page content String responseStr = EntityUtils.toString(entity, "UTF-8"); 

    This lets us authenticate to the Android Developer Console (version 2) site without requiring user credentials together with nosotros tin give the axe easily proceed to parse the upshot together with utilization it inwards a native app (warning: operate inwards progress!) from here. The downside is that for this to work, the user has to grant access twice, for 2 cryptically looking token types (SID together with LSID).

    Of course, after writing all of this, it turns out that the stock Android browser already has code that does it, which nosotros could remove hold used or at to the lowest degree referenced from the rattling beginning. Better yet, this discover leads us to an yet easier way to hit our task. 

    The piece of cake way

    The piece of cake way is found correct side past times side to the Browser degree referenced above, inwards the DeviceAccountLogin class, thus nosotros can't genuinely remove hold whatever credit for this. It is hardly anything new, but some Googling suggests that it is neither widely known nor used much. You mightiness remove hold noticed that the Android browser is able to silently log yous inwards to Gmail together with friends, when yous utilization the mobile site. The way this is implemented is via the 'magic' token type 'weblogin:'. If yous utilization it along alongside the service call together with URL of the site yous desire to access, it volition produce all of the steps listed higher upwards automatically together with instead of a token volition give yous a total URL yous tin give the axe charge to instruct automatically logged inwards to your target service. This magic URL is inwards the format shown below, together with includes both the ubertoken together with the URL of the target site, every bit good every bit the service call (this instance is for the Android Developer Console, line is broken for readability):

    https://accounts.google.com/MergeSession?args=service%3Dandroiddeveloper%26continue %3Dhttps://play.google.com/apps/publish/v2/&uberauth=APh...&source=AndroidWebLogin 

    Here's how to instruct the MergeSession URL:

    String tokenType = "weblogin:service=androiddeveloper&" + "continue=https://play.google.com/apps/publish/v2/"; String loginUrl = accountManager.getAuthToken(account,tokenType, false, null, null)                    .getResult().getString(AccountManager.KEY_AUTHTOKEN); 

    This is ane time again for the Developer Console, but plant for whatever Google site, including Gmail, Calendar together with fifty-fifty the line of piece of work organisation human relationship administration page. The only work yous mightiness remove hold is finding the service name, which is hardly obvious inwards some cases (e.g., 'grandcentral' for Google Voice together with 'lh2' for Picasa).

    It takes only a unmarried HTTP asking cast Android to instruct the concluding URL, which tells us that the token issuing catamenia is implemented on the server side. This way that yous tin give the axe also utilization the Google Play Services customer library to number a weblogin: 'token' (see screenshot below together with banker's complaint that dissimilar for OAuth 2.0 scopes, it shows the 'raw' token type). Probably goes without saying, but it also way that if yous occur to come upwards across someone's accounts.db file, all it takes to log inwards into their Google account(s) is 2 HTTPS requests: ane to instruct the MergeSession URL, together with ane to log inwards to their accounts page. If yous are thinking 'This doesn't impact me, I utilization Google two-factor authentication (2FA)!', yous should know that inwards this instance 2FA doesn't genuinely help. Why? Because since Android doesn't back upwards 2FA, to register an line of piece of work organisation human relationship alongside the AccountManager yous demand to utilization an application specific password (Update: On ICS together with later, GLS volition genuinely exhibit a WebView together with permit yous authenticate using your password together with OTP. However, the OTP is non required ane time yous instruct the original token). And ane time yous remove hold entered one, whatever tokens issued based on it, volition just operate (until yous revoke it), without requiring entering an additional code. So if yous value your account, hold your original tokens unopen together with revoke them every bit presently every bit yous suspect that your telephone mightiness live lost or stolen. Better yet, consider a solution that lets yous wipe it remotely (which mightiness non operate after your revoke the tokens, thus live certain to cheque how it plant before yous genuinely demand it).


    As nosotros mentioned above, this is all ClientLogin based, which is recent example with total source code. This integration complexity together with UI impedance mismatch are the problems that OAuth 2.0 support via the AccountManager initially, together with recently officially deprecated, together with mightiness live going away presently (EOL scheduled for Apr 2013). But some of the Android Google information sync feeds still depend on ClientLogin, thus if yous utilization it yous would in all likelihood OK for a while. Additionally, since the weblogin: implementation is server-based, it mightiness live updated to conform alongside the latest (OAuth 2.0-based?) infrastructure without changing the client-side interface. In whatever case, sentry the Android Browser together with Chormium code to hold upwards to date.

    Summary

    Google offers multiple online services, some alongside both a traditional browser-based interface together with a developer-oriented API. Consequently, at that topographic point are multiple ways to authenticate to those, ranging from form-based username together with password login to authentication API's such every bit ClientLogin together with OAuth 2.0. It is relatively straightforward to instruct an authentication token for services alongside a world API on Android, either using Android's native AccountManager interface or the newer Google Play Services extension. Getting the required session cookies to login automatically to the Web sites of services that produce non offering an API is nevertheless neither obvious, nor documented. Fortunately, it is possible together with rattling piece of cake to produce if yous combine the special 'weblogin:' token type alongside the service call together with the URL of the site yous desire to use. The best available documentation virtually this is the Android Browser source code, which uses the same techniques to automatically log yous inwards to Google sites using the account(s) already registered on your device.

    Moral of the story: interoperability is thus much easier when yous command all parties involved.

    0 Komentar untuk "Droidcedas : Unmarried Sign-On To Google Sites Using Accountmanager"

    Back To Top