Data Export API - Authorization
Overview
Before users can view data from an application that uses the
Data Export API, they must access Google Analytics using a Google
Account. Authorization starts when a user provides
a username and password (login credentials). Your application uses the login
credentials to request an authorization token from the Google Authorization
API. The URL for this request is
https://www.google.com/analytics/feeds
. Note
that analytics is part of the authorization URL as the specific
service being accessed.
The authorization process verifies three things:
- The user has supplied
the required credentials for their Google Account.
- The same credentials are linked to an Analytics user account.
- The user is authorized to access
the profile indicated in the data feed URL.
If the user is not authorized to view either
the account or the profile data, the server returns an error. Once the authorization
token is received, it can be used to access a user's data on their behalf,
without having to send credentials on subsequent requests.
The Google Analytics Export
API supports the following authorization services, all of which are described
in the Google Data API
Authentication Overview:
- ClientLogin username/password authentication, for applications that run
on a user's computer
- AuthSub proxy authorization
- OAuth authorization
Which Authorization Method Should You Use?
When writing an application that uses the Google Analytics Data Export API,
you should consider both the client library you are using as well as the purpose
of the application. The following table summarizes the three supported authentication
methods for the Google Analytics Data Export API, with the relevant libraries
and application purpose for each.
| |
Protocol
Support |
Java
Support |
JavaScript
Support |
| ClientLogin |
Yes |
Yes |
No |
| AuthSub |
Yes |
Yes |
Yes |
| OAuth |
Yes |
Yes |
Limited* |
*Because OAuth requires a signature, and the signature key cannot be kept secure in a JavaScript environment, there is no native support for OAuth in Javascript. However, JavaScript support for the OAuth Proxy is available in Shindig, where a Shindig server can make OAuth requests on behalf of a gadget. The OAuth proxy is currently supported in iGoogle. For more information on how to build a gadget using the Google Data client and the OAuth Proxy, see Creating a Google Data Gadget.
For more information on determining which type of authentication you should
use, see Getting
Started with Account Authorization.
Understanding ClientLogin
ClientLogin is the simplest way to access the Data Export
API; you simply provide your user name and password. Use ClientLogin in the
following situations:
- You are starting to explore the Data Export API and you want to get going
quickly, using your own credentials.
- You are building a single-user application that will be
installed on a computer, not on the web.
- You want to share your data with others. In this case,
you provide your own credentials to retrieve the data, and you share the
data results with other people, who do not log in to Analytics via your application,
but merely access the display of data you have provided.
Important: Do not use ClientLogin
if you are writing an application that runs on your computer to make requests
on behalf of 3rd party end users. Instead, use either AuthSub or OAuth, which
protects end users' private data. Because ClientLogin stores the user login
data, it should only be used in cases where that data is under the direct control
of the user (e.g. their personal computer).
ClientLogin is available in the following development
environments. Click on each link to see details.
-
HTTP Protocol Details
To request an authorization token through ClientLogin, send a POST request to the following URL:
https://www.google.com/accounts/ClientLogin
The POST body should contain a set of query parameters that look like parameters passed by an HTML form, using the application/x-www-form-urlencoded content type. These parameters are:
| accountType |
Type of account to request authorization for. The default
is GOOGLE, which is currently the only option
supported by Google Analytics. |
| Email |
The user's email address. It must include the domain (e.g.
joe@gmail.com). |
| Passwd |
The user's password. |
| service |
The Analytics service name is analytics. (For other service names, see the service name list.) |
| source |
A string identifying your client application in the form companyName-applicationName-versionID. |
Authorization Failure
If the authorization request fails, then the server returns an HTTP 401 Unauthorized status code.
Authorization Success
If authorization succeeds, the server returns an HTTP 200 OK status code, plus three long alphanumeric codes in the body of the response: SID, LSID, and Auth.
-
Java Client Library
To request an authorization token through ClientLogin, use:
AnalyticsService as = new AnalyticsService("analytics");
as.setUserCredentials("username@gmail.com", "password");
Note: Use the same token for all requests in a given session; don't acquire a new token for each Analytics request.
More Information on ClientLogin
Understanding AuthSub
AuthSub proxy authorization is used by web applications that need to access
a user's Google Account. With AuthSub, the website operator and the client
code never
see the user's username and password. Instead, the client obtains
special AuthSub tokens which it uses to act on a particular user's behalf.
For this reason you should use the AuthSub method if you are building a web
application to access data through other people's credentials. This ensures
you respect users' private data and adhere to our
Terms
of Service.
In addition, the end user can revoke access by the 3rd party access at any
time. Users can do this by logging in at http://google.com/accounts,
going to Personal Settings -> Security -> Change Authorized Websites,
and removing access for any of the listed services.
For detailed information, see the Authentication for Web Applications documentation.
Note: You should not use this method if you
want to login with your own credentials and share data with others.
This method of account access is available in the following development environments.
Click on each link to see details.
-
HTTP Protocol Details
An AuthSub request URL might look like:
https://www.google.com/accounts/AuthSubRequest?
&next=http://www.example.com/myApplicationPage.html
&scope=https://www.google.com/analytics/feeds/
&secure=0
&session=1
The URL contains the following parameters:
| next |
The URL of the page the user will be redirected to after logging into Google Accounts. This is typically the URL of your application. |
| scope |
Indicates that the application is requesting a token to access Analytics feeds. This parameter must be: https://www.google.com/analytics/feeds/ (URL-encoded). |
| secure |
An optional Boolean flag indicating whether the authorization transaction should issue a secure token (1) or a non-secure token (0). Secure tokens are available to registered applications only. |
| session |
Indicates whether the token returned can be exchanged for a multi-use (session) token. Set to 1 for multi-use sessions and 0 for none. |
After the user logs in, the AuthSub system redirects the user to the URL specified in the next query parameter of the AuthSubRequest URL. The AuthSub system appends an authorization token to that URL, as the value of the token query parameter. For example:
http://www.example.com/myApplicationPage.html?token=l0g3SVzK0Q4m3t9fj1QscYPiAJ-trg6WyvhPNYlGy_A
This token value represents a single-use AuthSub token. In this example, since session=1 was specified, this token can be exchanged for an AuthSub session token by calling the AuthSubSessionToken service with the single-use token in an Authorization header, as follows:
GET /analytics/feeds/accounts/default
Content-Type: application/x-www-form-urlencoded
Authorization: AuthSub token="l0g3SVzK0Q4m3t9fj1QscYPiAJ-trg6WyvhPNYlGy_A"
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14
Host: www.google.com
Accept: text/html, image/gif, image/jpeg, *; q=0.2, */*; q=0.2
Connection: keep-alive
The AuthSubSessionToken service response includes a Token header that contains the session token and an Expiration header that indicates how long the token will remain valid. Your application can then use the session token value in the Authorization header of subsequent interactions with Analytics.
-
Java
The following example shows what an AuthSub request might look like using the
Java client library:
String requestUrl = AuthSubUtil.getRequestUrl("http://www.example.com/RetrieveToken",
"https://www.google.com/analytics/feeds/",
false,
true);
String suggestAuthorization = "<p>MyApp needs access to your "
+ "Google Analytics account. "
+ "To authorize MyApp to access your account, "
+ "<a href=\"" + requestUrl + "\">log in to your "
+ "account</a>.</p>";
String oneTimeUseToken = AuthSubUtil.getTokenFromReply(requestUrl);
String sessionToken = AuthSubUtil.exchangeForSessionToken(oneTimeUseToken, null);
AnalyticsService as = new AnalyticsService("analytics");
as.setAuthSubToken(sessionToken);
The example above works as follows:
- A call is made to
AuthSubUtil.getRequestUrl
- The first parameter contains the "next" URL where your user will be redirected to after signing in. This is the URL
where your application resides, with a URL query parameter
token set to a string to be used as a one-time use token.
- The second parameter indicates the scope of the service being accessed for authorization, in this case, Analytics.
- The remaining parameters are booleans that describe what will be done with this token. The
false in the third argument
position states that the token will not be used securely. The true
in the fourth position states that the returned one-time use
token will be exchanged for a secure session token.)
- The
AuthSubUtil.getTokenFromReply method extracts the one-time use token from requestURL.
- The
AuthSubUtil.exchangeForSessionToken method swaps the one-time use token for a session token, which doesn't expire for several weeks and is good for any number of queries.The
first argument is the token, the second is either a PrivateKey or null. If the private key is not null, the token
will be used securely and the request to make the exchange will be
signed.
-
JavaScript Client Library (default authorization method)
Here's an overview of
the authorization process for a web-based JavaScript client:
- The web-based application calls the
google.accounts.user.login() method provided by the JavaScript library, passing it a scope value that indicates which Google service to use. For Analytics, the scope is "https://www.google.com/analytics/feeds".
- The client library sends the browser to the Google Account login page, where the user can enter their credentials to log in to the service.
- If the user logs in successfully, then the AuthSub system sends the browser back to the web application URL, passing along the authentication token.
- The JavaScript client library stores the token in a cookie and returns control to the client library function that called
google.accounts.user.login().
Note: In order for a web-based application to authorize
your user, the JavaScript Client library loader must be called before
the HTML page finishes loading. The client library calls a window.onload handler
to exchange this token for a multi session authorization token.
- When the client application subsequently calls JavaScript library
methods that interact with Analytics, the client library automatically
attaches the multi-session token to all requests.
Note: For the JavaScript client library to make authorized Analytics requests in a web browser, your page must contain an image that's hosted at the same domain as your page. It can be any image, even a single-pixel transparent image, but there must be an image on the page. If you
don't want the image to appear on your page, you can use the style attribute of the <img> tag to position the image outside the rendering area. For example: style="position:absolute; top: -1000px;"
The user.login method creates an authorization token that the
client library handles. The token remains valid until you revoke it by
calling google.accounts.user.logout():
function logMeOut() {
google.accounts.user.logout();
}
If you don't call logout(), the cookie that stores the
token lasts for two years, unless the user deletes it. The cookie is retained across browser sessions, so the user can close their browser and then reopen it
and come back to your client and they'll still be logged in.
However, there are certain circumstances in which a token can become invalid
during a session. If Analytics rejects a token, your client should handle the
error condition by calling logout() to remove the cookie containing the current token, and then call login() again to
acquire a new, valid token.
There are two other AuthSub methods that you may find useful in various contexts:
google.accounts.user.checkLogin(scope) indicates whether or
not the browser currently has an authorization token for the given scope.
google.accounts.user.getInfo() provides detailed information
about the current token, for debugging use.
For details about using JavaScript to interact with AuthSub, including
information on token management and on checkLogin() and
getInfo(), see the Using
"AuthSub" Authentication with the JavaScript Client Library document.
Tip: Provide a login button or other user input mechanism to prompt the user to log in manually. If you call google.accounts.user.login() in your application without prompting the user, the user will initially see a Google Accounts login page rather than your web page. If the user decides not to log in, then Google does not direct them back to your page. In this scenario, a user attempts to view your page but is instead re-directed to a Google Account login page, which might be confusing and frustrating.
More Information on AuthSub
Understanding OAuth
The OAuth authorization method is an open protocol
for authorization in both desktop and web-based applications. Like AuthSub,
OAuth enables the application to get an access token without ever handling
the user's credentials. Unlike AuthSub, you are required to register your
application with a security certificate in order to use OAuth. The OAuth
website contains a clear descripton of the most common use cases for OAuth.
Consider using OAuth in the following situations:
- You are developing your application as a gadget that will run on a website
that supports OAuth, or you are writing a gadget designed to run in an
OpenSocial environment. See Writing
OAuth Gadgets for details.
- You are developing your application to a variety of different clients (installed,
web, mobile).
- You are developing your application in an environment that uses a variety
of services from multiple providers.
More Information on OAuth