Building a File Upload Service to your Google Drive using OAuth 2.0

Munsif Musthafa
8 min readOct 16, 2018

--

This blog post will steer you through the technicalities of OAuth 2.0 and how to make use of the resource sharing capabilities.

Now this is one of those buzzwords that gets thrown around quite frequently, but majority of the internet users have no clue of this whatsoever. Before we look at what this OAuth is, first I’d like to start with the difference between authorization and authentication.

Simply put, Authentication is who you are and Authorization is what you are allowed to do. When elaborated, authentication verifies the user and decides if he/she is part of the system whereas, authorization is when the system knows you but needs to verify whether you are allowed to access a certain resource or not.

What is OAuth 2.0

OAuth or Open Authorization is a framework for delegated authorization. The specification mentions on how unrelated servers and services can safely allow authenticated access to their resources without actually sharing the any initial credentials. OAuth came into play to provide the online web application users (not only web application as time went by) with a seamless user experience. You use hundreds of websites daily, and are required to register yourself into at least half of them. It is not humanly possible to remember hundreds of different login credentials. This is one place where OAuth helps remove that pain point from your online experience.

Let’s look at this example below.

Life before OAuth

Imagine that a new viral social media site has emerged and you decide to signup for your fair share of fun. But sadly, once you logged in, you can’t seem to find any of your friends in that site. But the site tells you that if you let it access your contacts list from another mail provider, it will check and let you know if any of your friends are in this site and if not, send an email on behalf of you to ask them to join here. But the catch is that you have to type in your email address and password of the mail provider in this website, so that the social media site can log in on behalf of you to the mail provider and access your contact list there for further processing. How safe is this? Can you trust a 3rd party application with your personal credentials of another service provider?

Enter OAuth. OAuth has defined flows that allows for safe and secure resource sharing by delegating authorization with the users’ consent. OAuth 2.0 now provides authorization flows for web and desktop applications, and mobile devices. Let’s start with OAuth roles.

OAuth Roles

OAuth 2.0 defines four roles:

  • Resource Owner, is the user who authorizes an application to access their account. The client application’s access to the user’s account is limited to the “scope” of the authorization granted.
  • Client, is the application that wants to access the user’s account but it must be authorized by the user first then verified by the authorization server.
  • Authorization Server, verifies the identity of the user and issues access tokens to the client application.
  • Resource Server, contains the protected user accounts’ resources.

Abstract Flow of the Protocol

Abstract Flow of the OAuth 2.0 Protocol
  1. The application requests authorization to access some protected resources in the server where user is already authenticated and authorized.
  2. If the user authorized the request, the application receives an authorization grant after consent.
  3. The application requests an access token from the authorization server by presenting authentication of its own identity, and the authorization grant it received after user consent.
  4. If the client application’s identity is authenticated and the authorization grant is valid, the authorization server issues an access token to the application, completing the authorization.
  5. The client application requests the resource from the resource server by presenting the access token for authentication
  6. If the access token is valid, the resource server serves the resource to the client application

But the actual flow is dependant on which authorization grant type is used. A grant is a method of acquiring an access token. Let’s now look at what the 4 most used grant types are and let’s how we can implement a client application of our own.

Authorization Grant Types

  • Authorization Code Grant, is most commonly used for server-side applications. This is a redirection-based flow, meaning the application must be capable of interacting with the client browser to handle re-routes.
  • Implicit Grant, is used for single page web applications and mobile applications, where the client secret confidentiality is not guaranteed. This flow does not authenticate the identity of the application, and relies on the redirect URI provided while registering.
  • Resource Owner Password Credentials Grant, is where the user provides their username and password credentials directly to the client application. This should only be used if the application is trusted by the user (generally a mobile version of the same vendor of the web app).
  • Client Credentials Grant, provides an application a way to access its own resources and is used by client applications to obtain an access token outside of the context of a user.

Which one these grants to use is clearly described in the below flowchart.

https://oauth2.thephpleague.com/images/grants.svg

Next up we shall take a look at how to leverage one of these flows to build your very own OAuth-based client application.

Step I: Application Registration

First you must register your application with the service provider. This is done through a registration form in the “developer” portal of the service’s website (Google in our case), where you will provide the,

  • Application Name
  • Application Website
  • Redirect URI or Callback URL

Redirect URI is where the Google will redirect the user after he/she authorizes our application and is the part of the application that will handle authorization codes and/or access tokens. Once you have successfully registered your application, Google will provide your application with some credentials which include,

  • Client Id — this is publicly exposed for Google to identify your app
  • Client Secret — this is used to authenticate your app to Google (private)

Below are few snips of the steps of generating the client credentials for your application/ website by registering the application name and callback URI.

1. Create a project in the Google developer console

1. Create a project in the Google developer console

2. Enable the Google Drive API to generate your client credentials

2. Enable the Google Drive API to generate your client credentials

3. Click on Create Credentials button to start the progress

3. You will have to click on Create Credentials button to start the progress

4. Fill out the details of the client application

4. Fill out the forms where you are required to give the aforementioned attributes of the client website/application

5. Once completed, your client credentials will be generated

5. Once you have completed all the steps your client credentials will be created and registered in Google

Step II: Building the Client Application

The application we are building today will be using Authorization Code Grant Type to demonstrate the OAuth capabilities. The application is built using Spring Boot and the Google Client Library for OAuth and Drive, which makes things relatively easier (if you understand the API that is…)

Login page with Google SSO enabled

The user will need to be redirected to the consent page to give permissions for the application to make use of the user’s drive account. This is the request the Authorization Endpoint of Google expects from the client application,

https://accounts.google.com/o/oauth2/auth?access_type=offline& client_id=XXXXXXXXX.apps.googleusercontent.com&redirect_uri=http://localhost:8080/oauth/callback&response_type=code&scope=https://www.googleapis.com/auth/drive

The component query params of the url are as follow,

access_type — Indicates whether your application can refresh access tokens when the user is not present at the browser. Valid parameter values are online, which is the default value, and offline.

client_id — The client ID for your application

redirect_uri — Determines where the API server redirects the user after the user completes the authorization flow.

response_type — Expected response from the server. For Authorization Code, the value is code

scope — A space-delimited list of scopes that identify the resources that your application could access on the user’s behalf

When run, you are presented with the screen as below.

Selecting your user account and log in to it

The implementation of the above is shown in the below service and controller.

OAuthController.java
OAuthService.java

When the user is redirected to the Authorization Endpoint, Google will prompt the user with the below consent page where the user would allow or cancel the permission request.

Giving the View and manage the files in your Google Drive permissions to the client application

And redirected to the Homepage of your application based on the callback URI or the redirect URI you provided for your client application. The implementation for handling the callback is given in the above controller and service classes under the GetMapping for “/oauth/callback”.

Each request to upload a file to the Drive from the user’s browser is sent with an Authorization Header like Authorization: Bearer XXXXX where XXXXX is the Access Token the application has received from Google by exchanging the Grant Code. P.S. This happens internally when you use the Google client SDK like I did for this example.

You are redirected to the homepage after signing into Google Drive

Now you are free to upload any type of file to your Google drive with this very minimalistic application. You can find the complete implementation of this application in my GitHub repository.

For more information on building applications, leveraging the OAuth framework and the Google APIs, refer the following links.

See you in the next post. Ciao.

--

--