Following the launch of our new AdSense Management API we want to shed some light on the OAuth 2.0 authentication protocol for web applications, presenting examples for the languages that we are supporting at the moment of writing: Java, Python and PHP.
Background
We strongly recommend reading Using OAuth 2.0 to Access Google APIs to learn about the Google implementations of OAuth 2.0 before proceeding with this post.
Java
The Google APIs Client Library for Java features a powerful and easy to use OAuth 2.0 library.
Using the library is even easier with the GoogleOAuth2ThreeLeggedFlow helper class.
First create an instance of GoogleOAuth2ThreeLeggedFlow, passing the following parameters to the constructor:
- a key that will be used to associate this flow object with an end user
- the Client ID for your application
- the Client Secret for your application
- the scope you are requesting access to (AdSense in your case)
- the callback URL where the user should be redirected to in order to complete the flow
GoogleOAuth2ThreeLeggedFlow authFlow = new GoogleOAuth2ThreeLeggedFlow(
userId,
"INSERT_CLIENT_ID_HERE",
"INSERT_CLIENT_SECRET_HERE",
"https://www.googleapis.com/auth/adsense.readonly",
"http://example.com/path/to/auth_return");
To start the flow, get the authorization URL and redirect the user there:
String authUrl = authFlow.getAuthorizationUrl();
response.sendRedirect(authUrl);
If the user grants your application permission to access their data, they will be redirected to your callback URL and you’ll need to parse the authorization code from the request:
String authorizationCode = request.getParameter("code");
The last step is to use the authorization code to obtain an access token.
First you’ll need to initialize a transport for communication with the Authorization server and a factory for handling JSON, as the access token will be returned as a JSON object:
JsonFactory factory = new JacksonFactory();
HttpTransport transport = new NetHttpTransport();
authFlow.setHttpTransport(transport);
authFlow.setJsonFactory(factory);
Now you can finalize the authentication flow by obtaining credentials for your user, using those credentials to create the Adsense helper object and then sending your signed requests to the API:
Credential credential = authFlow.complete(authorizationCode);
Adsense adsense = new Adsense(transport, credential, factory);
AdClients adClients = adsense.adclients.list().execute();
Python
The home of the
Google APIs Client Library for Python is also the home of
OAuth2Client, a library designed for connecting to resources protected by OAuth 2.0.
First create an OAuth2WebServerFlow object, passing the following parameters to the constructor:
- the Client ID for your application
- the Client Secret for your application
- the scope you are requesting access to (AdSense in your case)
- an HTTP User-Agent to identify this application
flow = OAuth2WebServerFlow(
client_id='INSERT_CLIENT_ID_HERE',
client_secret='INSERT_CLIENT_SECRET_HERE',
scope='https://www.googleapis.com/auth/adsense.readonly',
user_agent='your-beautiful-python-app/1.0')
Now to start the flow you need to redirect the user to the Authorization URL, providing a callback URL where Google will send the authorization code. You will also need to serialize your flow object somewhere, as we will need to access it again after the redirection to the callback URL:
# in a multiuser environment, associate it to a specific user
# local to your application
store_flow(pickle.dumps(flow))
callback = 'http://example.com/path/to/auth_return'
authorize_url = flow.step1_get_authorize_url(callback)
request_handler.redirect(callback)
Back from the redirect, retrieve your OAuth2WebServerFlow object and proceed to step2, where the authorization code will be parsed from the request and used to request an access token:
flow = pickle.loads(retrieve_flow)
credentials = flow.step2_exchange(self.request.params)
Now you can create an an Http object and use the credentials to authorize it:
http = httplib2.Http()
http = credentials.authorize(http)
Now that your Http object is authorized, instantiate a service wrapper for the AdSense Management API and start querying the API:
service = build("adsense", "v1", http=http)
result = service.adclients().list().execute()
PHP
The
Google APIs Client Library for PHP enables PHP developers to work with Google APIs such as the AdSense Management API.
The
apiOAuth2 class implements the OAuth 2.0 web-server authentication flow for the PHP language.
To handle the OAuth2 web-server authentication flow in PHP you need to require the source for the apiClient and the source for the service class of the API that you are targeting, create and configure the apiClient for the authentication and then create the Adsense service:
require_once '../../src/apiClient.php';
require_once '../../src/contrib/apiAdsenseService.php';
$client = new apiClient();
// Visit https://code.google.com/apis/console to
// generate your oauth2_client_id, oauth2_client_secret, and to
// register your oauth2_redirect_uri.
$client->setClientId('YOUR CLIENT ID HERE');
$client->setClientSecret('YOUR CLIENT SECRET HERE');
$client->setDeveloperKey('YOUR_DEVELOPER_KEY_HERE');
// The oauth2_redirect_uri is typically the path
// to where you host this PHP file.
$this->client->setRedirectUri(‘YOUR_REDIRECT_URI_HERE’);
$adSense = new apiAdsenseService($client);
$client->setScopes(
array("https://www.googleapis.com/auth/adsense.readonly"));
Call ‘authenticate’ on the client to start the authentication flow. If the user is not yet authenticated, the application will receive an authorization code as GET parameter, and this will then be used by the client to request an access token, returned by authenticate.
All in this simple call:
$client->setAccessToken($client->authenticate());
And there is more. What happens when the access token expires? Nothing that you can perceive. The API client will use the refresh token to request a new access token for you, and you won’t even notice.
Once we are authorized, querying the AdSense Management API is simple as:
$result = $adSense->adclients->listAllAdclients();
That’s all folks! For now...
In this post we have seen examples of how to authenticate your web applications using the Google implementation of the OAuth 2.0 protocol and the libraries that we are providing to simplify all of the tasks involved.
But it’s not all, stay tuned to our blog: in the upcoming posts we will see how to authenticate with OAuth 2.0 using native applications and how to avoid repeated authorization requests for your users, in multi user environments.
If you have any questions about this or other topics, don't hesitate to visit
our forum.
- Silvano Luciani, AdSense API Team