OAuth 2, in simple English, is a simple protocol that makes it easy for third-party applications to access a user’s account without the user having to give out their username and password to the application. Let me explain with an example.
The Save Emails addon downloads email messages from a user’s Gmail account to their Google Drive. The addon is the third-party application in this case and it can use OAuth 2.0 to obtain permission from the user to access their Gmail and Google Drive via standard Google APIs. The user can revoke access to the addon anytime. Also, if the user changes the password of their Google account later, the OAuth 2 connection will continue to work.
The OAuth 2.0 flow is something like this.
- You create a new project in the Google Console for your application and generate the client ID and client secret. These keys are known both to your application and Google.
- Enable the various Google APIs that your application would use to obtain data from the user’s account. For instance, if you are the admin of a Google Apps domain, you may want to activate the Admin Directory SDK to get a list of all users in the domain.
- The application then redirects the browser to a URL on the Google server. Here the user needs to give consent on whether the application should be granted access to their data on not.
- If the user approves, the Google Authorization Server redirects the user back to your application with a single-use authorization code that can be exchanged for a short-lived access token and a refresh token.
- Store the tokens in Google Cloud Storage, Firebase, MySQL database or even the local filesystem for command line applications.
- All future requests to the Google APIs should include this access token. The access token expires after some time so your application can use the refresh token to obtain a new access token. The refresh tokens do not expire.
In the next section, we’ll build a simple web application that uses OAuth 2.0 with Gmail API and Google PHP library to generate a list of all labels in the user’s mailbox.