Sign In made easy — OAuth 2.0 Authorization Code Flow

Prakhar Chaube
WhatfixEngineeringBlog
7 min readDec 2, 2021

In this busy and pacing World, creating a new set of credentials for every website/community can be very cumbersome, to say the least! Filling out the typical details such as selecting a username, creating a strong password, and verifying the email address is not only time-consuming but also an increased overhead for the User. It leads to a mammoth task of Remembering/storing the credentials safely, which, mostly, means either having a common password across portals (like using Password as your password) or writing all of them in a single place (Single point of failure). So how did the smart folks of the Tech Industry tackle this problem, both, in terms of UX and Security? Let us visualise how it’s done along with some Java Code Snippets which will help you implement the same!

The Protocol behind the Scene: OAuth 2.0

Many of you would have guessed that one of the most commonly used Security Protocols, Open Authorization, has something to do with it!

OAuth is an open-standard authorization protocol or framework that provides applications the ability for “secure designated access”.

Well, in simple words, Oauth is a framework that allows one application to interact with another on your behalf, without the need for you to reveal your password.

Let us see how this simple yet robust protocol works!

How does OAuth work?

“Wait! If I do not reveal my password, how does the Third-Party Application authenticate me?” — John Doe

Yes, John raises an important problem here, and to solve this OAuth uses a neat trick! It creates a dynamic key, called the Access Token, which as the name suggests, provides Access to the desired data on behalf of the User! Each request to obtain any resource data from the server must have this Access Token attached in its header! The neat part is that this token expires periodically making it safer than your static password and can be regenerated using another token, called the Refresh Token.

Here is an example code snippet for using OAuth Access Token in JAVA:

// Assume a well designed class prior this snippetOkHttpClient client = new OkHttpClient().newBuilder().build();Request request = new Request.Builder()
.url("https://{domain}/{api-path}/{resource}")
.method(GET, null)
.addHeader("Authorization", "{access_token}")
.build();
Response response = client.newCall(request).execute();
System.out.println(response);
// Do something with the response! Don't just add comments like me!

That was about how the protocol OAuth 2.0 works in general. There are many flavors of OAuth2.0, each helping in a specific use case. In the following sections, we will explore how the ‘Authorization Code Flow’ makes the Sign-in process easy and secure!

Important terms:

  1. OAuth Service Provider: The platform that provides integration via OAuth 2.0.
  2. Client: The Application that will access resources on behalf of the user. (Example: Medium)
  3. User or Resource Owner: The user is whose data will be accessed.
  4. Authorization Server or OAuth Server: The Server belonging to the OAuth Service Provider will validate and authorize the Client via the User’s consent and return the Authorization code and Access Token. (Example: Google, Okta, etc.)
  5. Client Id: A unique identifier for the client, generated at the time of registration with the OAuth Service Provider. Can be exposed publicly.
  6. Client Secret: A unique key that is not available publicly, it is also generated at the time of registration with the OAuth Service Provider.
  7. Redirect Url: The Url to which the User will be redirected after Authorization. This is configured at the time of registration with the OAuth Service Provider.
  8. Authorization Code: Unique code returned as a query param in the Redirect Url in case of successful authorization.
  9. Grant Type: A code to define the way an application gets an access token, for example, it is authorization_code for requesting a set of the Access token and Refresh token.

The Authorization Code Flow in Action

At a very high level, the following happens in The Authorization Code Flow :

  • The Client prompts a login request to the User.
  • The User sees this and approves the request, usually via performing a login.
  • The User is redirected back to the application with an Authorization Code attached in the Redirected Url.
  • The Client extracts the Authorization Code and sends the request for obtaining an Access Token and Refresh Token.
  • The Access Token can now be used to fetch the required User data!

In the words of the fabulous Matthew McConaughey, “Alright! Alright! Alright! We are ready to dive into the technical aspect of the process”.

I can not be sure of the above quote, but can be of the following process:

  1. The User receives a login prompt to Authorize the Client. The prompt request comes from the Authorization Server itself, the link for which is usually of the following format:
    https://oauth-server.com/oauth-server-path/authorize?client_id={Client Id}&redirect_url={Redirect Url}&response_type=code&state={random character sequence to prevent CSRF Attack}
  2. After the User authorizes the Client, they are transitioned to the Redirect Url along with the Authorization Code and State attached as Query Params. Suppose your Redirect Url is https://www.my-redirect-url,
    in that case, your final landing page would be
    https://my-redirect-url?code={Authorization Code}&State={same random sequence of character as that of the request}
  3. At this point, the Client has been authorized and a unique code has been returned acknowledging the Authorization! Now the only remaining task is to send this Authorization Code to the Authorization Server along with the identity of the Client to obtain the final key to the treasure, i.e. the Access Token along with the Refresh Token.

Java code snippet to get Access Token using Authorization Code

// Example Snippet to fetch Access Token with Authorization Code using Unirest JAVAUnirest.setTimeouts(0, 0);HttpResponse <String> response = Unirest.post("https://authorization-server.com/oauth-path/token")
.header("Content-Type", "application/x-www-form-urlencoded")
.field("client_id", "{Client Id}")
.field("client_secret", "{Client Secret}")
.field("grant_type", "authorization_code")
.field("code", "{Authorization Code}")
.asString();
// Do Something with the response

Java code snippet to get Access Token using Refresh Token

// Example Snippet to fetch Access Token with Refresh Token using Unirest JAVAUnirest.setTimeouts(0, 0);HttpResponse<String> response = Unirest.post("https://authorization-server.com/oauth-path/token")
.header("Content-Type", "application/x-www-form-urlencoded")
.field("client_id", "{Client Id}")
.field("client_secret", "{Client Secret}")
.field("grant_type", "refresh_token")
.field("refresh_token", "{Refresh Token}")
.asString();
// Do Something with the response make Matthew McConaughey proud
OAuth 2.0 Authorization Code Flow Sequence Diagram — auth0

Sign In to Medium using Google Account

Now, to understand how The Authorization Code Flow helps us in Signing Up/In with Websites, let us analyze ‘Sign In Using Google’ for Medium.

  • The user is shown the prompt (usually a pop-up) to perform the login. If you look closely at the Url you will notice it is the Authorization Url containing Medium’s Client Id registered with Google OAuth Server.
Authorization Prompt
  • After Performing a successful login, the next prompt is a consent screen. This screen tells the User what all data will the Client application have access to along with all the actions it may perform on your behalf.
Sample Consent Screen, credits- Google Dev
  • Once you click allow, multiple back-end processes take place.
  • You will notice that the pop-up is then redirected to a different page for a fraction of a second, before closing. Usually, the Redirect Url points to a page containing some javascript code to do three operations, extracting the Authorization code from the Url, sending this code to the parent process responsible for initiating the OAuth2.0 process, and closing the pop-up.
  • Now, the server has the Authorization Code and it makes the final call needed to fetch the Access Token.
  • Once the Access Token is fetched, the application makes the relevant calls to fetch the Data and you land up on the home page!
  • In the subsequent Sign Ins, you do not see the Consent screen as you have already authorized the Client application.
Final Landing Page after Signing In with Google Account

When to use the Authorization Code Flow

The Authorization Code flow is best used in web and mobile apps for obtaining User Information.

It provides an extra layer of security by the need to obtain Authorization Code which is missing in Implicit Grant flow.

If using the Authorization Code flow in a mobile app, or any other type of application that can’t store a Client Secret, then you should use the PKCE extension, which protects against other attacks where the authorization code may be intercepted.

Do remember that the OAuth2.0 Authorization Code Flow is not the same as User Session Management. User Session Management is utilized for communicating between the frontend and the backend of the Client Application whereas, the OAuth2.0 Authorization Code Flow is employed for communication between two Backend Systems, the Client Application, and the OAuth Provider (In this example, Google).

Tip: Always provide appropriate scope when trying to fetch the Access Token. In most cases, only ‘Basic Details’ of a User are needed. Proper scope limits the attack surface on the User’s Data in case of a compromised Access Token.

The Authorization Code Flow at Whatfix

At Whatfix, we utilize OAuth 2.0’s Authorization Code Flow for establishing connections between the User and Whatfix. At Whatfix we both fetch data from the User’s Application (Repository Integration) and also create Whatfix Content to the User’s Application (Integration Hub). OAuth Integration provides a cleaner and smoother onboarding experience with minimal effort required from the User.

--

--

Prakhar Chaube
WhatfixEngineeringBlog

So many things to learn, so many thoughts to pen. Software Engineer, Stock Market Enthusiast, Musician, Dreamer, Human.