Skip to main content
RESTful Principles
CHAPTER 16 Beginner

OAuth 2.0 Basics

Updated: May 13, 2026
5 min read

# CHAPTER 16

OAuth 2.0 Basics

1. Introduction

We've covered API keys and JWTs, but what if you want to let users log into your app using their Google, Facebook, or GitHub accounts? You can't ask the user for their Google password—that would be a massive security violation. Instead, we use a framework called OAuth 2.0. In Chapter 16, we will demystify the OAuth flow, explain how third-party authorization works, and differentiate between Access Tokens and Refresh Tokens.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Define what OAuth 2.0 is and what problems it solves.
  • Understand the roles in OAuth (Resource Owner, Client, Authorization Server, Resource Server).
  • Explain the Authorization Code Flow.
  • Differentiate between Access Tokens and Refresh Tokens.
  • Understand why OAuth relies heavily on HTTPS and Redirect URIs.

3. Beginner-Friendly Explanation

Imagine you stay at a fancy hotel, and you want the hotel's valet to park your car. You don't give the valet the master key to your house and your car (your password). Instead, you give the valet a special "Valet Key" (an OAuth token) that *only* lets them start the car and drive it a short distance. It doesn't let them open the trunk or enter your house.

In software, OAuth allows a user to give an application (like your API) limited access to their data on another server (like Google) *without* giving away their master password.

4. Real-World Examples

  • "Log in with Google": When a new app asks to "View your basic profile info and email address" via a Google popup.
  • Zapier Integrations: When you connect Slack to Google Calendar, Zapier uses OAuth to get permission to read your calendar and post messages to your Slack, without knowing the password to either.

5. Detailed Code Examples

Implementing a full OAuth server from scratch in PHP is extremely complex. Usually, you use a library. However, conceptually, receiving an OAuth token looks like this:
php
1234567891011121314151617181920212223242526
<?php
// 1. The user was redirected back to our site from Google with a "code"
$code = $_GET[&#039;code'] ?? null;

if ($code) {
    // 2. We secretly trade this code for an Access Token by making an API call to Google
    $postData = [
        &#039;client_id' => 'OUR_APP_ID',
        &#039;client_secret' => 'OUR_APP_SECRET',
        &#039;code' => $code,
        &#039;grant_type' => 'authorization_code',
        &#039;redirect_uri' => 'https://ourapi.com/callback'
    ];

    // Using cURL to POST to Google's Token Endpoint
    $ch = curl_init(&#039;https://oauth2.googleapis.com/token');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
    $response = curl_exec($ch);
    
    // 3. Google gives us the JSON containing the Access Token
    $tokens = json_decode($response, true);
    
    echo "Success! We got the Access Token: " . $tokens[&#039;access_token'];
}
?>

6. Request/Response Examples

When the token trade happens (Step 2 above), the response from the OAuth server looks like this:
json
1234567
{
  "access_token": "ya29.a0AfB_byC...",
  "expires_in": 3599,
  "refresh_token": "1//04xD1e...",
  "scope": "https://www.googleapis.com/auth/userinfo.email",
  "token_type": "Bearer"
}

7. HTTP Examples

The OAuth flow relies heavily on HTTP Redirections (302 status codes).
  1. 1. Your app redirects the user to https://google.com/oauth?clientid=123
  1. 2. User logs in to Google and clicks "Allow".
  1. 3. Google redirects the user back to your app: https://yourapp.com/callback?code=secretcode

8. JSON Examples

Once you have the access_token, you use it exactly like the Bearer tokens we learned about in Chapter 13. You put it in the header to ask Google for the user's data.
http
123
GET /oauth2/v2/userinfo HTTP/1.1
Host: www.googleapis.com
Authorization: Bearer ya29.a0AfB_byC...

9. Best Practices

  • Use the Authorization Code Flow: For web and mobile apps, always use the flow that involves a code and a clientsecret. Never use the "Implicit Flow" (which puts tokens directly in the URL), as it is highly insecure and deprecated.
  • Strict Redirect URIs: In your Google/Facebook developer console, you must strictly define where the server is allowed to redirect the user after login. This prevents hackers from intercepting the code.

10. Common Mistakes

  • Confusing OAuth with Authentication: OAuth 2.0 is technically an *Authorization* framework (granting permissions). OpenID Connect (OIDC) is the layer built on top of OAuth that handles actual *Authentication* (proving identity).
  • Leaking the Client Secret: Your clientsecret is like the master password for your app. If you build a React/Vue app, NEVER put the clientsecret in your frontend JavaScript code. It must live securely on your PHP backend.

11. Mini Exercises

  1. 1. What is the difference between an Access Token and a Refresh Token?
*(Answer: The Access Token is used to get data, but it expires quickly (e.g., 1 hour). The Refresh Token is a long-lived key used ONLY to get a new Access Token when the old one expires, so the user doesn't have to log in again).*

12. Coding Challenges

Challenge 1: Write the HTTP Header required to make an API request using an OAuth access token with the value 12345-abcde.

13. MCQs with Answers

Question 1

What is the primary purpose of OAuth 2.0?

Question 2

Which token is used to obtain a new access token when the current one expires?

Question 3

Where should your clientsecret be stored?

14. Interview Questions

  • Q: Explain the step-by-step process of the OAuth 2.0 Authorization Code flow.
  • Q: Why do Access Tokens expire quickly, and how does the Refresh Token solve the UX problem of users having to constantly log in?
  • Q: What is the difference between OAuth 2.0 and OpenID Connect?

15. FAQs

Q: Do I need to build an OAuth server? A: Usually, no. You will mostly be an OAuth *Client* (consuming Google/Facebook APIs). Building an OAuth *Provider* (allowing other apps to "Log in with YourApp") is incredibly complex and usually requires enterprise packages like Laravel Passport or specialized services like Auth0 or Okta.

16. Summary

In Chapter 16, we explored OAuth 2.0. We learned that it is a secure delegation framework that allows apps to access data on behalf of a user without knowing their password. We walked through the redirect flow, understood the difference between short-lived Access Tokens and long-lived Refresh Tokens, and highlighted the importance of keeping your client_secret safe on the backend.

17. Next Chapter Recommendation

We know how to authenticate users via our own database or via Google. But once they are authenticated, how do we restrict what they are allowed to do inside our API? Proceed to Chapter 17: REST API Authorization to learn about Role-Based Access Control.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·