← Back to list

Choosing the Right OAuth 2.0 Grant Type. A Scenario-Based Guide

Apply the Right Grant Type to Your Use Case

Isuru Cumaranathunga in CodeX · 2024-10-13 16:13 · 5 claps · 15.6 min read
#oauth2 #grant-types #authorization-code #client-credentials #single-sign-on
Open on Medium ↗
Wiki topics: LIT · Literature & Writing

Choosing the Right OAuth 2.0 Grant Type. A Scenario-Based Guide

Apply the Right Grant Type to Your Use Case

Goal of OAuth 2 illustration

Goal of OAuth 2 illustration

If you are using free-tier, then you can view this article using this link.

Quick intro to OAuth and the problem it addresses

OAuth 2.0 is an open authorization framework that enables applications (clients) to obtain limited access to user accounts on an HTTP service, such as Facebook, GitHub, or Google, without exposing user credentials (like passwords). The key players in OAuth 2.0 are

  • Resource Owner: The user who owns the data and can grant access.
  • Client: The application requesting access on behalf of the user.
  • Authorization Server: The server that authenticates the user and provides access tokens to the client.
  • Resource Server: The server that holds the user’s resources (data) and responds to requests once access has been granted.

Rather than forcing users to share their passwords across multiple services, OAuth 2.0 allows for controlled access via a system of tokens. These tokens allow specific access to certain parts of a user’s data for a limited time without ever needing to reveal their login credentials.

Before OAuth, apps that wanted to access a user’s data had to store user credentials, creating a variety of security and privacy issues:

  • Credential Sharing: Users were often required to provide their username and password to third-party services.
  • Overprivileged Access: There was no way to limit what the service could do once it had the user’s credentials; it could access anything tied to the account.
  • Lack of Revocation: Once a user shared their credentials, there was often no way to revoke access without changing their password entirely.

OAuth 2.0 addresses these issues by introducing a secure and standardized way to delegate access without sharing sensitive credentials. For example, when you authorize a third-party app to access your Google account, the app only gets the permissions you explicitly grant, such as reading your email, and you can revoke this access at any time.

OAuth 2.0’s Solution for the above problem.

OAuth 2.0 introduced a safer, more efficient solution to these problems by eliminating the need for apps to handle user credentials directly. It replaced password-sharing with access tokens, which are temporary, limited tokens that represent the user’s authorization.

The key benefits OAuth 2.0 provides are:

  • Tokenized Access: The client app only receives a token, which can be scoped to specific resources and access levels.
  • Revocable Access: Users can revoke access at any time without needing to change their passwords.
  • Granular Permissions: OAuth 2.0 allows users to grant specific permissions to third-party apps, limiting the risk of overprivileged access.
  • Delegated Authorization: The user can grant an app access to their data without ever sharing their actual credentials.

The grant types

Now that we’ve explored why OAuth was introduced and the solutions it provides, let’s talk about a key player in the OAuth 2.0 landscape: tokens. Tokens are essential for accessing resources, whether it’s user data or services. To obtain a token, OAuth introduces several methods, known as grant types.

But why do we have multiple grant types? Each one is designed to tackle specific challenges and scenarios that arise in different situations. Understanding these grant types will empower you to choose the right one for your application’s needs.

Here’s a quick overview of the most common grant types you’ll encounter:

  • Authorization Code Flow with PKCE: Perfect for web and mobile app users, ensuring secure authorization.
  • Client Credentials: Ideal for server-to-server communications where user involvement isn’t required.
  • Device Code: Great for devices with limited input capabilities, like smart TVs or IoT devices, allowing users to authenticate on another device.
  • Refresh Token: Used to renew access tokens without requiring the user to log in again, enhancing user experience.

Additionally, there are two legacy flows to be aware of:

  • Implicit Flow: Designed for client-side applications but now considered less secure.
  • Password Flow: Allows users to provide their credentials directly to the client but poses security risks.

With this foundation laid, let’s dive deeper into each grant type and see how they can be applied in real-world scenarios!

TeamCollab: A Productivity SaaS Platform

TeamCollab is a collaborative productivity platform designed for teams to manage tasks, schedules, and files. It allows users to integrate their Google services (e.g., Google Drive, Google Calendar) to boost productivity. Employees can access TeamCollab from web browsers, mobile apps, or even smart boards in meeting rooms. The platform is integrated with third-party services like Google for file storage and email syncing.

At a high level, TeamCollab has several internal services that handle task management, user authentication, and integration with external APIs. There’s an Authorization Server that manages how users log in and get their tokens, and internal services that handle task lists, notifications, and file storage connections. Web and mobile apps (clients) communicate with TeamCollab’s API. The system also connects to external APIs like Google Drive to access user files on behalf of the user.

The example TeamCollab platform and its interaction with other systems

The example TeamCollab platform and its interaction with other systems

1. Authorization Code Flow with PKCE (for Web and Mobile App Users)

Imagine you’re logging into TeamCollab on your phone or browser to check your tasks or manage shared Google Drive files. To do that securely, you need a token that proves to TeamCollab you are who you say you are. Without a token, the app can’t interact with TeamCollab’s internal services or the Google services that store your files. That’s where the Authorization Code Flow with PKCE comes in.

Let me walk you through the process, step by step:

  1. Login Begins: You open TeamCollab on your phone. You hit “Log in with Google,” and you’re redirected to the Google login page.
  2. Google Authentication: You enter your Google username and password directly on Google’s site, not on TeamCollab. This is the key! TeamCollab never touches your password.
  3. Authorization Request: After logging into Google, Google asks you if you want to allow TeamCollab to access your Google Drive and Calendar. You grant permission, and Google gives TeamCollab a temporary authorization code.
  4. PKCE Security Check: Before TeamCollab asks Google for an access token (which allows TeamCollab to interact with Google Drive on your behalf), it generates a code verifier and a code challenge. These are part of PKCE (Proof Key for Code Exchange). They ensure that only your phone (or browser) can exchange that authorization code for an access token, even if someone tries to intercept the authorization code.
  5. Why PKCE Matters: Without PKCE, if someone intercepted that authorization code, they could use it to pretend to be you and get access to your files. With PKCE, the intercepted code would be useless because the attacker wouldn’t have the correct code verifier to complete the exchange.
  6. Exchanging the Authorization Code: Now, TeamCollab takes the authorization code (which proves Google trusts TeamCollab to access your data) and sends it to Google, along with the code challenge. If everything matches, Google sends back an access token and a refresh token.
  7. Access Token in Action: The access token is what TeamCollab uses to access your Google Drive files or calendar events whenever you request them. For example, when you click on a project that has shared Google Drive files, TeamCollab uses this token to securely access those files on your behalf. You can think of the token as a temporary key that opens the door to your Google Drive.
  8. Refresh Token: After a while, the access token expires (for security reasons, tokens have short lifespans). But you don’t want to log in again every time this happens, right? That’s where the refresh token comes in. When the access token expires, TeamCollab uses the refresh token to get a new one without bothering you.

Authrization code flow with PKCE for the TeamCollab

Authrization code flow with PKCE for the TeamCollab

What actually happens in the PKCE is first the client will generate a code and Hash it (With SHA-256). Then sends the hashed result along with the request to the Auth server. Then later when client submits the authorization code, it must send the previously generated code (pure code before getting hashed). Then the authorization server will apply the SHA-256 and verify whether it equals to the previously received Hashed code(at the first request).

Why This Flow Matters

Now, imagine if there was no Authorization Code Flow. You would be logging into TeamCollab and entering your Google email and password directly into TeamCollab’s app. This would lead to serious security risks:

  • Credential Sharing: TeamCollab would need to store your Google username and password, making it a prime target for attackers. If TeamCollab is hacked, your Google credentials (and any other users’) would be exposed.
  • Overprivileged Access: Once you share your Google credentials, TeamCollab would have full access to your entire Google account — not just the parts you authorized. Without a way to scope the access (like tokens), the app could read all your emails, change settings, or worse.
  • No Revocation: If TeamCollab were compromised or you stopped trusting it, the only way to revoke its access would be to change your Google password, which would be a huge inconvenience.

2. Client Credentials Flow in TeamCollab

Let’s say TeamCollab provides an automated backup service for companies. This service periodically backs up all team-related documents and project files stored in Google Drive to a secure internal storage system (within TeamCollab). Since this backup task needs to happen on behalf of the company and not on behalf of a specific user, no individual user needs to log in. Instead, TeamCollab itself acts as the client, needing access to the company’s Google Drive storage for this scheduled task.

Here, we use the Client Credentials Flow, where TeamCollab (the client) directly requests a token from Google’s authorization server to access company files for backups.

Step-by-Step Flow:

  1. TeamCollab Identifies Itself: When it’s time to perform the backup, TeamCollab’s internal service reaches out to Google’s authorization server. Since there’s no specific user involved, it identifies itself using its client ID and client secret, which are like the app’s credentials. These credentials were issued by Google when TeamCollab integrated with Google Drive as a trusted client.
  2. Token Request: TeamCollab sends a request to Google’s authorization server, saying, “Hey, I’m TeamCollab, and I need access to Google Drive for backups. Here’s my client ID and secret.”
  3. Token Issuance: Google’s authorization server verifies TeamCollab’s credentials (client ID and client secret) and, if everything checks out, issues an access token.
  4. Accessing the Resources: TeamCollab takes the access token and uses it to access the company’s Google Drive. It retrieves the documents and project files necessary for the backup and stores them securely in its internal storage.
  5. Token Expiration: Just like in the Authorization Code Flow, the token has an expiration time. When the token expires, TeamCollab can request a new token using the same client credentials without any user intervention.

Why Client Credentials Work Here

Now, you might wonder: “Why is it okay to use a client ID and client secret to get a token in this scenario?”

Let’s break it down:

  1. No User Involvement: In this scenario, no specific user is involved. The backup service is purely a machine-to-machine operation. It’s TeamCollab, as a system, interacting with Google Drive to retrieve files. Since no user is logging in, we don’t need to worry about user credentials, login screens, or handling sensitive user data.
  2. Why Client ID and Client Secret are Safe: TeamCollab uses its client ID and client secret (think of these as app credentials) to authenticate itself with Google. These credentials are securely stored on TeamCollab’s servers and never exposed publicly. This is a safe and standard practice because:

It’s secure: The client secret is stored securely on the server, not shared with end users or exposed in insecure environments (like browsers or mobile devices).

No human interaction: Since this process doesn’t involve a user logging in, there’s no risk of password sharing or phishing.

Automated process: The service can run automatically without requiring any manual steps or user intervention, which is ideal for background tasks like backups.

  1. Machine-to-Machine Authentication: The Client Credentials Flow is designed exactly for this kind of use case where one system (TeamCollab) needs to authenticate itself to another system (Google) and access resources without any user interaction. This flow is perfect for scenarios like background services, data syncs, or system-level integrations where no human needs to be involved.

3. Device Code Grant in TeamCollab

Imagine TeamCollab is installed on a large smartboard in your company’s meeting room. Team members can use the smartboard to manage tasks, review project timelines, or even access shared Google Drive files during meetings. However, the smartboard doesn’t have a keyboard or a convenient way to log in. You can’t type in your email and password on a large screen, especially in front of everyone.

In this situation, we need a way to let users securely log into TeamCollab on the smartboard, without directly entering credentials on the device itself. This is where the Device Code Grant flow comes into play.

The Device Code Grant is designed for devices like TVs, smartboards, or other gadgets that don’t have an easy input method for typing usernames and passwords.

Step-by-Step Flow:

1.Initiating the Login: A user walks up to the smartboard in the meeting room, taps on the TeamCollab app, and selects “Log in to TeamCollab.” Instead of showing a keyboard or asking for credentials, the smartboard displays a unique code (let’s call it a device code) and a URL like [https://login.teamcollab.com/device.](https://login.teamcollab.com/device.) This can be put into a QR code and ask the user to scan the QR code with another device.

2.User Action on Another Device: The user is instructed to take out their phone or laptop (something that has a proper keyboard and browser) and navigate to the displayed URL. There, they’re asked to enter the device code that’s shown on the smartboard.

For example, the smartboard might show something like: “To log in, go to https://login.teamcollab.com/device and enter the code: ABC123.”

Or else Scan the QR code which will navigate to the above url with the code embedded in the URL

3.Authentication on a Personal Device: Once the user opens the URL on their personal device (phone or laptop) and it redirects the user to the login page. After they authenticate successfully. Here if user’s tries to access the Google drive files then the TeamCollab’s auth service will redirect the user to the respective Google’s login and then Google asks for their permission to allow TeamCollab (on the smartboard) to access their Google Drive and other resources.

4.Granting Permission: After the user consents, TeamCollab’s Authorization server provides an access token to TeamCollab, which can then be used on the smartboard. TeamCollab automatically detects that the login process is complete and grants access to the user’s files and tasks on the smartboard. Here SmartBoard App keeps polling the TeamCollab’s auth service by checking whether user has logged in or not.

5.Access Granted: The smartboard, now having received the token, can use it to interact with TeamCollab services without the user ever having to type in their credentials on the device itself. The user is securely logged in, and the smartboard can now be used to manage tasks, review files, and collaborate in real-time.

How device grant is used in a smartboard

How device grant is used in a smartboard

Why Device Code Grant is Used Here

The Device Code Grant flow solves a very specific problem: how to log into devices that don’t have a user-friendly way to enter text, like smartboards or even TVs. Here’s why this flow is particularly useful:

  1. Input Limitation: Devices like smartboards or TVs aren’t designed for entering usernames and passwords easily. The Device Code Grant allows users to authenticate using another, more convenient device (like their phone or laptop) where they can comfortably log in and grant access.
  2. No Credential Exposure: Since the user is never entering their credentials directly on the smartboard, there’s no risk of their password being exposed or compromised on a shared or insecure device. They’re only logging in via a trusted, personal device like their phone or computer.
  3. Separation of Device and Authentication: The device code separates the login process from the device itself. The smartboard or other limited-input device just needs to display the code and wait for the user to authenticate on another device. Once the authentication is completed on the personal device, the smartboard is granted access, but it never sees the user’s password or other sensitive information.

The Device Code Grant flow in TeamCollab provides a perfect solution for scenarios where users need to authenticate on devices with limited input capabilities, like smartboards, while keeping their credentials secure and the process user-friendly.

4. Refresh Token Flow in TeamCollab

Let’s say you’ve logged into TeamCollab through the web app using the Authorization Code Flow. You’re working on a project and accessing your Google Drive files via TeamCollab. The access token TeamCollab received from Google has an expiration time — let’s say it’s valid for one hour. After that hour, the token will expire, and you won’t be able to continue accessing your Google Drive files unless you get a new token.

This is where the Refresh Token Flow comes in handy.

How the Refresh Token Flow Works:

  1. Initial Token Issuance: During the initial login (e.g., using the Authorization Code Flow), TeamCollab’s authorization server issues both an access token and a refresh token. The access token is used to communicate with Google’s APIs, and the refresh token is stored securely by TeamCollab for later use.
  2. Access Token Expiry: After an hour, the access token expires. Normally, you would need to go through the entire login process again to get a new access token, but since TeamCollab was also given a refresh token, it can use this to renew the access token automatically.
  3. Token Renewal with the Refresh Token: When TeamCollab notices that your access token has expired, it sends a request to the authorization server with the refresh token. The server verifies the refresh token and issues a new access token without requiring you to log in again.
  4. Continued Access: With the new access token in hand, TeamCollab can continue to access your Google Drive files seamlessly, without interrupting your workflow or making you log in again.

Why the Refresh Token Flow is Useful

The Refresh Token Flow provides a smooth user experience by avoiding frequent logins. Here’s why it’s beneficial:

  • No Need for User Re-authentication: Once logged in, the user can continue working without having to re-enter credentials every time the access token expires.
  • Long-Term Access: The refresh token allows TeamCollab to renew access tokens in the background, ensuring uninterrupted access to resources over extended periods.
  • Security: The refresh token itself is usually long-lived and can be securely stored on the server, minimizing the risk of exposure to the client or malicious actors.

Legacy Grant Types: Password Grant and Implicit Grant in TeamCollab

When OAuth 2.0 was first introduced, some systems were still heavily reliant on users providing their usernames and passwords to third-party services. To enable a smooth transition from these old methods to OAuth 2.0, the Password Grant and Implicit Grant were introduced. These grant types provided a way for existing systems to migrate to OAuth 2.0, but over time, as more secure and robust flows were developed, they became legacy and are no longer recommended for modern applications.

1. Password Grant (Resource Owner Password Credentials Grant)

How it works: The Password Grant allows a user to provide their username and password directly to the client (in this case, TeamCollab), which then sends those credentials to the authorization server to obtain an access token.

  • In TeamCollab’s case: If we were to use the Password Grant flow, when a user logs into the TeamCollab web app, they would be asked to enter their Google username and password directly into TeamCollab. TeamCollab would then pass those credentials to Google’s authorization server and receive an access token to access the user’s Google Drive files.

Why it’s not recommended This method exposes the user’s credentials to the client app (TeamCollab), which completely defeats the purpose of OAuth 2.0’s primary goal — avoiding the sharing of credentials with third-party services. It increases the risk of a security breach, as TeamCollab would now be responsible for handling and protecting user credentials, which could be exposed or misused.

Why other grant types are better The Authorization Code Flow with PKCE ensures that the user’s credentials are never shared with TeamCollab. Instead, authentication is handled directly between the user and the trusted authorization server (like Google), which returns a token to TeamCollab. This keeps credentials secure and out of TeamCollab’s hands.

2. Implicit Grant

How it works: The Implicit Grant is a simplified version of the Authorization Code Flow, where the access token is returned immediately without the need for exchanging an authorization code. This grant type was primarily designed for client-side (JavaScript) applications where storing a client secret wasn’t secure or feasible.

  • In TeamCollab’s case: If we used the Implicit Grant flow for our web app, when a user logs in, TeamCollab would receive the access token directly in the browser after they authenticate with Google, without any further token exchange.

Why it’s not recommended The Implicit Grant has security vulnerabilities because the access token is exposed directly in the browser, making it more susceptible to being intercepted by malicious actors. Since there’s no client secret involved, it’s easier for attackers to obtain access tokens and compromise security.

Why other grant types are better The Authorization Code Flow with PKCE ensures that the access token is exchanged server-side, keeping it out of the client (browser) and adding an extra layer of security with the PKCE code challenge. This makes the entire flow more secure, especially for public clients like web or mobile apps.

While the Password Grant and Implicit Grant served a purpose during the early days of OAuth 2.0 to help older systems transition, they are now legacy and deprecated for modern applications. By using secure grant types like Authorization Code Flow with PKCE, Client Credentials, Device Code, and Refresh Tokens, TeamCollab ensures a more secure and robust experience for its users.

You’ve Mastered OAuth 2.0 Grant Types!

Congratulations! You’ve now got a solid understanding of the OAuth 2.0 grant types and how they apply to real-world projects, just like our hypothetical TeamCollab solution. Whether it’s securing a web or mobile app with the Authorization Code Flow with PKCE, letting backend services talk securely using the Client Credentials Flow, enabling device-based logins with the Device Code Flow, or keeping sessions alive with the Refresh Token Flow, you’ve covered the essentials of modern, secure access management.

By learning how to apply these grant types in your applications, you’re not just improving the user experience, but also contributing to making the digital world a safer place. OAuth 2.0 provides a robust framework for ensuring that user credentials stay private, access is controlled and revocable, and different devices can communicate securely.

As you continue building applications, make sure to choose the right OAuth 2.0 grant type for each situation. By doing so, you’re helping raise the bar on security standards across the web, creating a more secure environment for everyone.

Thanks for taking this journey into OAuth 2.0 grant types with me! Stay tuned for another scenario-based article covering another exciting software engineering topic soon. Keep learning, keep building, and let’s continue making the world a safer and more innovative place together!

Until next time! 👋


메타데이터
post_id
6bcbcfa7cce9
slug
choosing-the-right-oauth-2-0-grant-type-a-scenario-based-guide-6bcbcfa7cce9
url
https://medium.com/codex/choosing-the-right-oauth-2-0-grant-type-a-scenario-based-guide-6bcbcfa7cce9
canonical_url
https://medium.com/codex/choosing-the-right-oauth-2-0-grant-type-a-scenario-based-guide-6bcbcfa7cce9
author_url
https://medium.com/@isurucuma
status
ok
fetched_at
2026-08-24 22:42:17