OAuth 2.0 for native applications

Following our previous post on OAuth 2.0 for web applications, we are now taking a look at how to use the OAuth 2.0 authentication protocol for native applications, presenting examples for the languages that we are supporting at the moment of writing: Java and Python.
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. We can take advantage of the existing GoogleOAuth2ThreeLeggedFlow helper class to easily perform our authentication flow.

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 URI to redirect to
GoogleOAuth2ThreeLeggedFlow authFlow = new GoogleOAuth2ThreeLeggedFlow(
  userId, 
  "INSERT_CLIENT_ID_HERE", 
  "INSERT_CLIENT_SECRET_HERE", 
  "https://www.googleapis.com/auth/adsense", 
  "urn:ietf:wg:oauth:2.0:oob");

For native applications, we use a special redirect URI:

"urn:ietf:wg:oauth:2.0:oob"

The “oob” part stands for “out of band” and the rest of the string identifies it as a part of the OAuth 2.0 standard.

When we use this redirect URI, instead of redirecting the user’s browser to a page on our site with an authorization code, Google will display a page and the authorization code or error response in the title of the page. A text field contained in the page will show instructions for the user to copy and paste it into our application.

To start the flow, let’s ask the user to load the authorization URL in their browser:

System.out.println(“Please input authorization code: ”);
Scanner in = new Scanner(System.in);
String authorizationCode = in.nextLine();

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, and then use those credentials to create the Adsense helper object and then send 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',
  user_agent='your-beautiful-python-app/1.0')

We can perform the authentication calling the ‘run’ function imported from oauth2client.tools, storing the authentication data using a Storage object:

storage = Storage(‘adsense.dat’);
credentials = run(flow, storage);

If the flag ‘auth_local_webserver’ is raised (the default setting), oauth2client.tools will open the authentication URL on a running browser or on the system default browser. After the user performs the authentication, the authorization code will be read from the title of the page shown in the browser. If you don’t want this behaviour, you can disable it like this:

import gflags
gflags.FLAGS.auth_local_webserver = False

In this way we’ll have a flow similar to the one that we have seen in Java: the user will be asked to open the authentication URL in a browser window and then to copy and paste the authorization code back in the application. The only difference is that oauth2client.tools will take care of printing these messages and read the input from the user for us.

The last step is create an httplib2.Http object, authorize it with the previously obtained credentials and then send a request to the API:

http = httplib2.Http()
http = credentials.authorize(http)
service = build(‘adsense’, ‘v1’, http=http)
result = service.adclients().list().execute()

Cool! But I want to know more!

In this post we have seen examples of how to authenticate your native application using the Google implementation of the OAuth 2.0 protocol and the libraries that we are providing to simplify all of the tasks involved.

Now that we know how to perform authentication for both web and native applications, in my next post we are going to see different ways of storing the authentication data.

Google+ Pages – Already HERE!

Google helps to grow your audience by connecting you with new users. They introduced the +1 button so your site would stand out on search and your users could easily share your content on Google+. But, sometimes you want to join the conversation and post content directly to where people are sharing.

Today they’re introducing Google+ for Business, a collection of tools and products that help you grow your audience. At the core of this is Google+ Pages, your site’s identity on Google+.

Google+ Pages: Have real conversations with the right people

To get your site on Google+, you first need to create a Google+ Page. On your page, you can engage in conversations with your visitors, direct readers back to your site for the latest updates, send tailored messages to specific groups of people, and see how many +1’s you have across the web. Google+ Pages will help you build relationships with your users, encouraging them to spend more time engaging with your content.



Google+ Pages are at the heart of Google+ for Business

Hangouts


Sometimes you might want to chat with your users face-to-face.  For example, if you run a food blog, you may want to invite a chef to talk about her favorite recipe, or if you manage a fashion review site, beauty specialists might want to hold how-to sessions with makeup tips. Hangouts make this easy, by letting you have high-quality video chats with nine people with a single click. You can use Hangouts to hold live forums, break news or simply get to know people better, all in real time.



Hangouts let you meet your customers, face-to-face

Circles


Circles allow you to group followers of your Page into smaller audiences. You can then share specific messages with specific groups. For example, you could create a Circle containing your most loyal readers and offer them exclusive content.

The Google+ badge: Grow your audience on Google+
To help your users find your page and start sharing, there are two buttons you can add to your site by visiting our Google+ badge configuration tool:

The Google+ icon, a small icon that directly links to your Page.

 

 


The Google+ badge, which we’re introducing in the coming days. This badge lets people add your page to their circles without leaving your site, and allows them to get updates from your site via Google+.

Extend the power of +1, stand out in Google search
You can also link your site to your Google+ page so that all your +1s — from your Page, your website, and search results — will get tallied together and appear as a single total. Potential visitors will be more likely to see the recommendations your site has received, whether they’re looking at a search result, your website, or your Page, meaning your +1’s will reach not only the 40 million users of Google+, but all the people who come to Google every day. You can link your site to your Page either using the Google+ badge or with a  piece of code. To set this up, visit our Google+ badge configuration tool.

Bringing Google+ to the rest of Google


Our ultimate vision for Google+ is to transform the overall Google experience — weaving identity and sharing into all of our products. Beginning today, we’re rolling out a new experimental feature to a small group of eligible publishers,Google+ Direct Connect — an easy way for your audience to find your Google+ Page on Google search.  If you’ve linked your Page to your site and you qualify, when someone searches for your website’s name with the ‘+’ sign before it Direct Connect will send them directly to your Page. For example, try searching for ‘+YouTube’ on Google. Users will also be prompted to automatically add Pages they find through Direct Connect to their circles.



Direct Connect suggestions start populating as you type on Google.com


Just the beginning

We want to help you get your site on Google+ as soon as possible, so we’re opening the field trial for Google+ Pages to everyone today. Creating a Google+ Page only takes a few minutes. To get started, you’ll need a personal Google+ profile. If you don’t have a Google account, it’s very quick and easy to join. And if you’re looking for inspiration, check out some of the sites that are already starting to set up their Pages:

To learn more about how Google+ works for your site, check out the Google+ Your Business site. We’re just getting started, and have many more features planned for the coming weeks and months. To keep up to date on the latest news and tips, add the Google+ Your Business page to your circles. If you have ideas on how we can improve Google+ for your site, we’d love to hear them.

 

Cross posted from the Inside AdSense blog

Start with the Google+ API

The Google+ project brings the nuance and richness of real-life sharing to software. The Google+ platform brings that nuance and richness to all of the web. We started with Google’s own products, added the +1 button for site owners and content publishers, and introduced games from a handful of partners. That’s just the beginning though — we want every one of you who builds applications to be able to include rich sharing, identity, and conversations in your app. Today, we’re taking the next step on that journey by launching the first of the Google+ APIs.

Let’s Go Public

Google+ gives users full control over their information, supporting everything from intimate conversations with family to public showcases and debates. This initial API release is focused on public data only — it lets you read information that people have shared publicly on Google+. For example, if you want to get my profile information, you can use the people.get method by sending the following HTTP request:

GET https://www.googleapis.com/plus/v1/people/108189587050871927619?key=yourAPIKey

which returns the following JSON encoded output (excerpted for brevity):

[php]{
"kind": "plus#person",
"id": "108189587050871927619",
"displayName": "Chris Chabot",
"image": {
"url": "https://lh5.googleusercontent.com/-cQNLOQzkGpE/AAAAAAAAAAI/AAAAAAAAEjo/M9_pXL-ra4Q/photo.jpg"
},
"organizations": [
{
"name": "Google+ Developer Relations",
"title": "Developer Advocate & Manager",
"type": "work"
}
]
}[/php]

Similarly, you can get a list of my most recent public posts by using the activities.list method:

 

GET https://www.googleapis.com/plus/v1/people/108189587050871927619/activities/public?key=yourAPIKey

Because we’re starting with public data only, you simply need to register your app before making requests. And if you aren’t yet sure which Google+ user is running your app (for example, because they’re installing it for the first time), then you can use the new plus.me OAuth2 scope to ask the user who they are.

After your application has requested this scope, you can use the special “me” identifier rather than the long numeric identifier:

GET https://www.googleapis.com/plus/v1/people/me

On The Shoulders of Giants

We love the way the programmable web has evolved, so we’re using existing standards and best practices wherever we can:

  • Our API methods are RESTful HTTP requests which return JSON responses.
  • Our payload formats use standard syntax (e.g. PoCo for people info, ActivityStrea.ms for activities).
  • We use OAuth 2 for secure trusted access to user data.

In addition, since most of us no longer write raw HTTP requests these days, we provide libraries for your favorite language: Java, GWT, Python, Ruby, PHP, Objective-C, and .NET. These libraries are all open source, so we’d love to have your feedback and help with them.

developers.google.com

You can find more information about the Google+ platform, including today’s new APIs to public data, at developers.google.com/+ on our new Google Developers site. This site will be the place to go for access to documentation, terms and policies, discussions with other developers, tools that make development on the +Platform easier and more fun and, of course, the place where announcements concerning new releases will be made.

Included in our policies are three simple guidelines that we aspire to in our own products, and that we’d like all applications built on the Google+ platform to follow also: put the user first, be transparent, and respect user data. The goal behind these guidelines, as with all of the features and fine print, is to work together to build products that our users will love.

And now …

For all of you developers who have been asking for a Google+ API, this is the start. Experiment with it. Build apps on it. Give us your feedback and ideas. This is just the beginning; the Google+ platform will grow and we value your input as we move Google+ forward.