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.

The DO’s and DON’Ts of Google Summer of Code: Student Edition

As Google Summer of Code mentoring organization administrators, we are the people who ensure Google Summer of Code runs smoothly within our organizations. Over the past 6 years, contributors to our four open-source projects (Gentoo, KDE, XMPP, and X.Org) have read more than 1,000 student applications and mentored hundreds of successful, and unsuccessful, students.

Based on our experience with Google Summer of Code, we’ve built cultural and community practices that strongly favor successful student projects, integration of code, and conversion of students to long-term contributors. We’ve also seen a lot of things go wrong—repeatedly. We’d like to share these tips and antipatterns with you to raise awareness and help students avoid the same mistakes when taking part in the program. For even more advice, check out the student guide.

DO DON’T
Be on your best behavior. Clear, respectful communication is just as important to success today as it was 100 years ago. When you write email or chat on IRC, use complete sentences without any SMS abbreviations (but acronyms are allowed, especially on IRC). If you are unsure about your English skills, there are tools available to help you, such as spell checkers and grammar checkers. On a related note, people want to work with others whose company they enjoy. Be friendly and polite; it’s hard to be too much of either. Make a bad first impression: SMS speech, extremely poor English, rudeness/hostility, etc. These fall into two major categories: failure to communicate and inability to get along with other people. Poor first impressions can seriously damage your chances because both of these problems derail collaboration, which is vital to a successful project. Entirely adequate programmers fail Google Summer of Code because of failures to communicate.
Read all the documentation, so you submit a useful application. Your application should provide all the detail necessary to convince people that you can accomplish your project, and you’re the best person to do it. That means showing you have experience, proving you’ve done research, and providing a concrete plan. Submit a useless application. Many varieties of entirely unhelpful applications exist: the one-sentence wonder, the proposal pasted directly from the ideas page, the free-form text that ignores an application template, and the application submitted to the wrong organization.
Be transparent about other commitments. When organizations know about your commitments in advance, you can work with them to develop a plan that deals with your schedule. For example, you could begin your work at a slower pace during the community-bonding period. If another commitment comes as a surprise to your mentor during the summer, you might not be able to compensate for it. Disappear. If your mentor thinks you have disappeared during the summer, this tends to quickly result in failure. The most common problem is failing to mention long family vacations or class schedules in the summer. Disappearing includes taking the initial payment and running with it; if you’re tempted to do this, you might want to consider the damage to your reputation, or the excited students missing out on a slot so you can waste yours.
Make Google Summer of Code your top priority. During the 12 weeks of coding time, nothing should take precedence over your project, and you should have no major distractions. If you have another job, decide whether you prefer it or Google Summer of Code and pick one. Make your choice early enough to leave your slot open for another student. Hold another major commitment. For example, if you have a second job without telling anyone until the start of coding, it’s a major problem. Anything outside of the program that takes more than 5–6 hours a week causes problems; this includes classes that extend through the coding period. Two simultaneous full-time jobs is unrealistic.
Be realistic about your skills. Think through your past experience. If you have trouble fairly assessing your abilities, just write about your coding experience instead and your org can make its own judgment. Additionally, some orgs will gladly provide small sample tasks that you can perform to judge how easy you’ll find the summer-long projects. Over- or under-rate your abilities. As long as you have some programming skill and are able to communicate well (see above), you should be suitable for some projects. This doesn’t mean that every student is equal if they meet these requirements. Overselling yourself leads to disappointment; underselling yourself the same.
Commit and publicize your code frequently. Discussing your code early and often, with your mentor and the broader community, is vital to the success of your project. Make small, easily recoverable mistakes early rather than huge ones when it’s too late to do anything about them. Make last-minute (or later) code drops. Showing your code in public can be scary. Some students wait until the very last minute to show their code to their mentor and other contributors to the project. Do this only if you have a burning desire to fail, because it’s too late for any review to fix holes in your code.
Submit code that’s ready to integrate. The best thing about an open source project is seeing your own code shipped in a release and used by thousands or even millions of people. This requires some effort on your part, however. You should closely track how other developers change related code so yours can be easily added to the latest development branch as soon as—or even before—the summer ends. During the last few weeks, make sure your code is polished enough so it’s ready to add to the project’s main repository; this may require documentation or test suites. Don’t let your summer’s work go to waste. Finish the summer with code that’s “almost ready” but will take forever to ship. Many students leave their project in a state that is very close to being shippable but isn’t quite there yet. Since the mentor tends to be too busy to finish it, these projects ship very slowly, if ever. It’s your project—you need to make it see the light of the day. This can require you to keep driving the project, and not trust that the mentor will keep on top of it once the summer is over.
Complete your project design before writing a line of code. Work with your mentor to define the architecture of your project before you begin coding. You don’t need to go as far as prototyping every function, but you should have a vision of how it will all eventually work at a reasonable level of detail, such as important data structures and algorithms. Determine the libraries and tools you’ll use, and be able to justify your choices. Start coding before finalizing design. You can hit major dead-ends when you haven’t yet finished working with your mentor to design the project, but you choose to begin coding anyway. For example, if you start coding for a NoSQL backend but your mentor and the rest of the community determine that a standard SQL database should be used, this can necessitate rewriting a lot of code for no reason. Changes on the architectural level can be even more disruptive to any code you’ve written prematurely.
Use your resources wisely. Help is just an email away. Don’t be afraid to ask questions when you get stuck; we don’t expect you to be an expert, and we’re happy to answer your questions. On the other hand, remember to do some basic research on your own before asking, such as searching the project documentation, the source code, and Google. Refuse to ask for help. Throughout the whole program, you will encounter problems that need to be solved—some of them small and some of them large. You can waste days stuck on a problem that can be solved in an hour by talking to other team members.
Remember that you’re part of a community. Very little in Google Summer of Code is 100% independent work. You may propose your project design, but you’ll develop it with the help of your mentor and community. You’ll write the code, but others will review it, and you’ll often build upon their previous work. Unlike school, where a grade could be your first feedback, in Google Summer of Code your grade (pass/fail) is your last feedback. By designing and developing your project in collaboration with your entire open-source community, you’ll get people excited about using your work and ready to integrate it. You’ll also give yourself the best chance of passing the program by receiving thorough reviews from your community and responding to them. Many students choose to continue contributing after the summer ends because of their interactions with the community. Consider it a solo project, like it often is in college. It’s not; you write the code, but your mentor is there to help with plans, designs etc. Your mentor is not like a lecturer or course leader at a college or university. There’s a whole community of people working on the project together, and you should interact with them as a whole. Don’t feel like you’re working for your mentor, you’re working for the community and your mentor is helping guide you, they are not your only point of contact. This has other implications too—other people will be working on the code base while you are, and you will see improvements happening around you as you code. You may need to keep your development branch up to date to take advantage of these.

Making Google Summer of Code the best possible program requires a commitment to excellence from participants at every level. In addition to committing to the program, you must also be thoroughly prepared.

In this post we’ve provided suggestions for students, and in later posts in this series we’ll cover mentors and admins. Whatever role you would like to play in Google Summer of Code or a similar program, read everything you can find so you know what you’re getting into. Good luck, and have fun in your endeavors.

NJ Historical Society Criticized for Selling Map

The New Jersey Historical Society is catching flak for auctioning off its copy of Abel Buell’s 1784 map of North America last month, the Star-Ledger reports. Apparently selling items to pay for operations — or, in the case of the Society, to go towards retiring its $2.6 million debt — is a violation of the code of ethics of the American Association of Museums. The Society’s annual grant has also been eliminated due to state budget cuts, so they’re clearly starving for cash. The Buell map the only item being sold off; the Society’s board president says all the items are extraneous to their mandate.