How to Integrate Users Into Your App With Google OAuth 2.0

How to Integrate Users Into Your App With Google OAuth 2.0

15 min read
Tags:

Usernames and passwords have become an integral part of our society as more and more of our daily lives take place online. You might have hundreds, or even thousands of accounts scattered across the internet and they each have their own (hopefully unique) username and password combination. This method has served us fairly well for a long time, but as modern society becomes more security conscious in light of numerous high-profile data breaches, passwords are turning out to not be as good of a solution for a variety of reasons. As a result, app developers are increasingly turning to OAuth to authenticate user accounts because it provides much better security through secure delegated access that uses access tokens rather than username and password credentials. 

OAuth 2.0 is the standard that most apps and services follow today, including Google.  In this post, you will learn how to integrate with the Google APIs via OAuth 2.0 so you can enable users to log into your app using their Google account.

Contents:

What is OAuth?

The vast majority of apps and services have used basic username and password authentication for most of software development history. However, this creates problems when you want to give an app access to data or functionality that’s stored inside another service that requires account authentication. This requires the app to store the user’s password, creating a password anti-pattern because passwords are meant to be protected secrets, meaning they shouldn’t be shared with anyone.

Consider this example: Alice wants to grant Bob access to her house to water her plants while she’s away on vacation. The typical solution is for Alice to give Bob a physical key that unlocks all exterior doors to the house. This poses some problems:

  • Bob must be trusted with a master key to the exterior doors, which is a fairly large amount of trust to give someone. What happens if it gets lost or stolen?
  • What if Bob wants to throw a giant party against the wishes of Alice? His access is unrestricted, meaning Alice can’t control things like the days or times Bob is allowed to enter the house.
  • What if Bob makes a copy of the key, but Alice wants to remove his access when she returns from vacation? Alice would need to change the locks.

Let’s compare this to an authentication scenario where app Alice gives app Bob a user’s username and password to let app Bob access data and functionality from app Alice: 

  • The security system of app Bob must be trusted to protect the account’s username and password. This significantly increases your user’s threat vectors.
  • App Bob is granted complete control over the account for app Alice. There’s no way to restrict what data and functionality app Bob can access.
  • The only way to ensure that Bob’s access to the user data is revoked is for the user to change their account password in App Alice.

OAuth solves these problems by allowing the end user of app Bob to interact directly with the identity provider service in app Alice and create a cryptographically-signed token that grants access to specified scopes. This token is given to the app Bob which, in turn, uses it authenticate requests to app Alice made on behalf of the user.  

Here’s how OAuth would operate in our scenario above:

  1. App Bob prompts the user to login with their account on app Alice, and redirects them to the authorization server for app Alice. App Bob provides a list of scopes that indicate the specific data and functionality app Bob needs to access.
  2. App Alice prompts the user to consent to the the scopes app Bob requested and generates OAuth credentials.
  3. App Alice redirects the user back to app Bob, which then initializes the authentication flow to retrieve user access tokens. 

Now, let’s take a look at how OAuth works with the Google APIs and how you can integrate it into your app.

How to Authenticate Google Accounts To Your App

There are two primary reasons why you might want to build a Google OAuth integration:

  1. If you want to access user data and functionality for your user’s benefit across Google accounts like Gmail, Google Calendar, Google Drive, etc.
  2. If you want to verify a user’s identity using their Google account to enable them to login to your app.

There are a few key concepts you need to understand to work with Google OAuth: how Google manages OAuth credentials, how user access tokens work, the scopes Google supports and how they handle permissions, and how to make API requests to the Google APIs.

OAuth Credentials

Before you can make any requests, you’ll need to head over to the Google API Console to setup a Google API project. Once you have your own project, you will need to enable the APIs you’d like to use and create the appropriate authorization credentials. These credentials vary depending on the type of authentication flow you use (more on that below), and any Google APIs you want to access. Take a look at the docs for the specific Google API you want to use to learn about how to setup your Google API project.

Access Tokens

Access tokens are unique strings that grant access to user data and functionality for all Google APIs. A single access token can provide a variety of degrees of access to any number of Google APIs. Access tokens are restricted to specific resources and operations based on the scopes that have been granted to them.

Scopes

Scopes control the data and functionality that are available for a user’s access token. When the user logs in with their Google account, they are prompted to consent to the scopes your app requests. If they grant one or more permissions, the Google authorization server will return an access token to your app that provides a list of scopes that token grants. If you have a Google account, chances are that you’ve seen something like this:

The Google OAuth Consent Process

Google recommends you request scopes incrementally at the time they are required by user actions. For example, if you want to support sending an email from a user account, your app should only request that functionality when the user does something within your app that requires the permission. In other words, don’t request every scope possible. Not only does Google frown upon this practice, but it’s also not a good user experience because its off putting if an app requests obtrusive permissions for basic functionality. Think about it this way, would you want your flashlight app to have the ability to delete your entire contacts book?

Google also recommends that you examine the list of scopes after the user consents to make sure your app doesn’t present functionality that you don’t have the appropriate scopes to fully support. The user can pick and choose which permissions they want to provide so, for example, if the user only consents to let your app read their email inbox, you shouldn’t enable functionality designed to let them send an email.

Make API Requests & Manage Refresh Tokens

Once your app has an access token, you can use it to make HTTP requests to the appropriate Google APIs; Google recommends sending this in the HTTP request header as a bearer token. Google account access tokens have limited lifetimes, so if you need to continue making requests for user data beyond the life of the access token, you also need to obtain a refresh token. The refresh token should be stored securely for long term use and can be used to generate future access tokens.

In the next section, we’ll explore the various OAuth authentication flows the Google APIs support.

Google OAuth API Authentication Flows

The Google APIs offer a few options to authenticate user accounts into your app. The most common are for server-side apps, client-side JavaScript, and service accounts. Let’s take a look at these one-by-one.

Server-Side Authentication

If you need to access and store sensitive user information or functionality, you should use server-side authentication. Server-side authentication is intended for apps that run on web servers, and is also referred to as the OAuth authorization code flow. Google recommends this method for most use cases because it’s the most secure way to implement OAuth. If you’re investigating a Google OAuth integration, you should start here first.Illustration of the Google server-side authentication process that implements OAuth Authorization Code flow

Here’s the process:

  1. Your app redirects a user to a specific Google URL that includes the list of requested permissions as URL query parameters. Check the list of Google Oauth 2.0 scopes to learn about what’s available.
  2. The user is prompted to consent to the permissions your app requests. They can pick and choose which permissions they want to allow.
  3. Google redirects your user back to your app and provides an authorization code
  4. Your app exchanges this code for an access token; the Google API returns a list of scopes the user has consented to and an access token that grants access to them.
  5. Your app uses this token to make requests for data and functionality via the appropriate Google APIs.

Benefits: This is the most secure method to authenticate user accounts via Google OAuth, and this is also viewed as a best practice for OAuth in general.

Downsides: This method requires you to store sensitive information both temporarily (account access tokens) and long term (refresh tokens).

Head over to the docs to learn more about OAuth authentication to the Google API for server-side apps.

Client-Side Authentication

If your app only needs brief access to information from a user account, you can consider client-side authentication. This method is primarily intended for client-side JavaScript, and uses a process called implicit grant flow, where the access token is returned to the client object immediately. This is intended for apps that don’t store confidential information, and that only access Google APIs while the user is actively interacting with the app. This can be a good solution if you only need to access basic information about the user, such as their email address and name, or to confirm their identity.

Illustration of Google client-side Oauth that follows the implicit auth flow

Client-side authentication has a fairly similar process to server-side authentication, but there are some key differences. Here’s how it works:

  1. Your app redirects a user to a specific Google URL that includes the list of requested permissions as URL query parameters. Check the list of Google Oauth 2.0 scopes to learn about what’s available.
  2. The user is prompted to consent to the permissions your app requests. They can pick and choose which permissions they want to allow.
  3. Google redirects your user back to your app and provides an access token that grants access to the user account.
  4. Your app uses this token to make HTTP requests to Google APIs.

Benefits: This is a very simple method to quickly get an access token for an account to access basic user data and functionality.

Downsides: This is generally not recommended as a secure practice, so you shouldn’t use it to access sensitive user information. This also is not a good solution for integrating large amounts of user data because your user will need to re-authenticate on a regular basis as their access tokens expire.

Take a look at the official Google OAuth docs to learn more about client-side authentication.

Service Accounts

If you’re building an app that only works for a single Google organization, then you can use service accounts. Service accounts are accounts that belong to a Google API application rather than individual end-users. In this scenario, consent is not required for any users that are a member of the associated Google organization. In other words, if you want to enable IT administrators to connect every account in their organization and manage company-wide settings, the service account authentication flow is what you need. This also allows your app to access data for an application itself for things like the Google Cloud Datastore API.

Illustration of Google Service Account Oauth

To start, you need to create a service account, then your server app should implement the following authentication flow:

  1. Create a JSON Web Token (JWT) that includes the requested scopes, signature, and encryption methods.
  2. Use the JWT to request an access token from the Google OAuth API server.
  3. Receive and store the access token from the Google OAuth API and verify the list of scopes and expiration time.

Benefits: This is a great solution if your app only needs to integrate with Google organizations because it allows IT admins to easily manage API access to all accounts within their organization.

Downsides: This method inherently requires some technical administrative overhead to manage the Google organization. Particularly if you want it to work with more than one Google organization.

Head over to the Google OAuth docs to learn more about how to use the service accounts authentication flow.

Other Authentication Flows

The Google API also supports authentication for mobile and desktop apps and device apps for things like TVs and game consoles. Google also provides client libraries that are simpler to implement for Android and iOS.

Nylas Makes Google Integrations Easy and Maintenance-Free

The Nylas Communications Platform integrates with 100% of email, calendar, and contacts providers, including Gmail, Google Calendar, and Google Contacts. With Nylas, you can build a full email, calendar, and contacts integration in a fraction of the time it would take to build a direct integration with the Google APIs. Let’s take a look at the features Nylas offers to make it dead simple to build your first email, calendar, and contacts integration.

Nylas Hosted Auth

Nylas Hosted Auth is the quickest and easiest way to setup user authentication for your app. Simply redirect users to a Nylas login page and we’ll handle the rest including auto-detection of third party providers and managing token exchanges, and refresh token storage with providers like Google.Illustration of the Nylas Hosted Auth service that integrates with 100% of email, calendar, and contacts providers, including Google

The Nylas Hosted Auth process is very similar to authentication with the Google API, but with some added magic to make your life much easier.

  1. Your app redirects a user to Nylas Hosted Auth and provides a list of email, calendar, and contacts scopes you would like to access.
  2. Nylas auto-detects the email account provider, and initializes the appropriate authentication process with the third-party API. In the case of Google accounts, Nylas initializes the Google OAuth consent process.
  3. After the user logs in to their account, Nylas redirects them back to your app, and returns the appropriate OAuth credentials. If you’re building a server-side app, Nylas returns an authorization code that can be exchanged for a user access token. If your app is client-side, Nylas returns the access token directly.
  4. Your app uses the access token to make requests to the Nylas Email, Calendar, and Contacts APIs on behalf of the users.

There are two key components of Nylas Hosted Auth that makes development easier:

  • Nylas auto-detects 100% of email, calendar, and contacts providers, even for Google organizations that use their own company domain for their email accounts. Additionally, you can connect user accounts for any other third party email, calendar, and contacts provider with no additional development work.
  • Nylas handles negotiating with third party providers to manage OAuth credentials like the Google refresh tokens to ensure user accounts are always connected and synced. The access token Nylas provides doesn’t expire until your app revokes it.

Focus on The Features Your Users Love

Ultimately, Nylas allows you to more quickly build your email, calendar, and contacts integration so you can spend more time building the features your users love. There’s no need to become an expert at Google API integrations when you build with Nylas

Get Started With Nylas

Here are some resources to help you learn how to get started with Nylas.

Related resources

How to Send Emails Using an API

Key Takeaways This post will provide a complete walkthrough for integrating an email API focused…

How to build a CRM in 3 sprints with Nylas

What is a CRM? CRM stands for Customer Relationship Management, and it’s basically a way…

How to create an appointment scheduler in your React app

Learn how to create an appointment scheduler in your React app using Nylas Scheduler. Streamline bookings and UX with step-by-step guidance.