Skip to content
What is OAuth 2.0 — Simple Explanation with Examples

What is OAuth 2.0 — Simple Explanation with Examples

DodaTech Updated Jun 20, 2026 6 min read

OAuth 2.0 (Open Authorization) is an authorization framework that enables applications to obtain limited access to a user’s resources on another service without exposing the user’s credentials. It is the standard behind “Sign in with Google” and “Login with GitHub.”

What You’ll Learn

This article explains the OAuth 2.0 roles, grant types, tokens, and a real-world flow. OAuth 2.0 is the backbone of modern delegated authorization — understanding it is essential for any developer building applications that integrate with third-party services.

The Problem OAuth Solves

Before OAuth, if you wanted App A to access your photos on Service B, you had to give App A your username and password for Service B. This created serious problems:

  • Password sharing — You gave your password to a third party. What if they stored it insecurely?
  • Unlimited access — App A could do anything your account allowed: read, write, delete.
  • No revocation — To revoke App A’s access, you had to change your password, which broke all other integrations.
  • Exposure risk — If App A was compromised, attackers got your actual password.

OAuth solves this by using tokens instead of passwords. You authorize App A with a scoped, revocable token that limits what App A can do.

The Hotel Key Card Analogy

A hotel room has a master key (your password) that opens the door to everything.

OAuth is like a hotel key card:

  • You check in (authenticate) at the front desk (authorization server).
  • You get a key card (access token) programmed for your specific room (scope).
  • The key card works only for certain doors (scopes): your room, the gym, but not the staff area.
  • The key card expires at checkout time (token expiration).
  • If you lose the key card, you get a new one without re-registering all guests (no password change).

OAuth 2.0 Roles

RoleDescriptionExample
Resource OwnerThe user who owns the dataYou
ClientThe application requesting accessA photo printing app
Authorization ServerIssues tokens after authenticationGoogle’s OAuth server
Resource ServerHosts the protected data, validates tokensGoogle Photos API

Grant Types

OAuth 2.0 defines several grant types (flows) for different scenarios:

1. Authorization Code Grant (Most Common)

Used for server-side web and mobile apps. It is the most secure flow for applications that can keep a secret.

1. User clicks "Sign in with Google"
2. App redirects to Google's auth URL:
   https://accounts.google.com/o/oauth2/v2/auth
     ?client_id=APP_CLIENT_ID
     &redirect_uri=https://myapp.com/callback
     &response_type=code
     &scope=email+profile
3. User logs in to Google and grants permission
4. Google redirects back to the app with a temporary code:
   https://myapp.com/callback?code=AUTH_CODE
5. App exchanges the code (plus client secret) for tokens:
   POST https://oauth2.googleapis.com/token
   {
     "code": "AUTH_CODE",
     "client_id": "APP_CLIENT_ID",
     "client_secret": "APP_SECRET",
     "grant_type": "authorization_code",
     "redirect_uri": "https://myapp.com/callback"
   }
6. Google returns access_token + refresh_token
   {
     "access_token": "ya29.a0AfH6S...",
     "token_type": "Bearer",
     "expires_in": 3600,
     "refresh_token": "1//0gABCDEF..."
   }
7. App uses the access_token to call Google APIs:
   GET https://www.googleapis.com/oauth2/v2/userinfo
   Authorization: Bearer ya29.a0AfH6S...

2. Implicit Grant (Legacy / Not Recommended)

Simpler but less secure — the access token is returned directly in the URL fragment. Used by SPAs before PKCE was introduced. Now deprecated in favor of Authorization Code with PKCE.

3. Client Credentials Grant

For server-to-server communication where no user is involved. The client authenticates with its own credentials.

curl -X POST "https://auth.example.com/token" \
  -H "Content-Type: application/json" \
  -d '{
    "grant_type": "client_credentials",
    "client_id": "MY_APP_ID",
    "client_secret": "MY_APP_SECRET"
  }'

Used by backend services and cron jobs.

4. Authorization Code with PKCE

PKCE (Proof Key for Code Exchange) extends the authorization code grant for mobile apps and SPAs that cannot securely store a client secret. The app generates a cryptographic challenge that it sends with the auth request and proves with the code exchange.

Access Tokens vs Refresh Tokens

TokenPurposeLifetimeCan be revoked?
Access TokenSent with every API call to authorize accessShort-lived (15 min–1 hour)Typically not
Refresh TokenExchanged for a new access token without user re-authLong-lived (days–months)Yes

Refresh tokens allow the app to maintain access transparently. When the access token expires, the app silently uses the refresh token to get a new one.

Example: “Sign in with GitHub” in a Node.js App

// Redirect user to GitHub authorization page
const authUrl = `https://github.com/login/oauth/authorize
  ?client_id=${process.env.GITHUB_CLIENT_ID}
  &redirect_uri=${encodeURIComponent('http://localhost:3000/callback')}
  &scope=read:user`;  // scope = what we want access to

// Callback route: exchange code for token
app.get('/callback', async (req, res) => {
  const { code } = req.query;

  // Exchange code for access token
  const tokenResponse = await fetch(
    'https://github.com/login/oauth/access_token',
    {
      method: 'POST',
      headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
      body: JSON.stringify({
        client_id: process.env.GITHUB_CLIENT_ID,
        client_secret: process.env.GITHUB_CLIENT_SECRET,
        code
      })
    }
  );
  const { access_token } = await tokenResponse.json();

  // Use token to fetch user profile
  const userResponse = await fetch('https://api.github.com/user', {
    headers: { Authorization: `Bearer ${access_token}` }
  });
  const user = await userResponse.json();

  // Now you have the user's GitHub data
  res.json({ name: user.name, avatar: user.avatar_url });
});

Security Considerations

  1. Always use HTTPS — Tokens in transit must be encrypted.
  2. Use short-lived access tokens — Limits damage if a token leaks.
  3. Use PKCE for mobile/SPA — Protects against authorization code interception.
  4. Validate redirect URIs — The server must only redirect to registered URIs to prevent open redirect attacks.
  5. Use state parameter — A random string sent with the auth request and verified on return prevents CSRF attacks.
  6. Never log tokens — Access and refresh tokens should never appear in logs or error messages.

Common Use Cases

  1. Social login — “Sign in with Google/Facebook/GitHub/Twitter” uses OAuth 2.0 to authenticate users without handling passwords.

  2. API access delegation — A SaaS app integrating with a user’s Google Drive or Dropbox uses OAuth to request specific file access scopes.

  3. Mobile banking integrations — Budgeting apps (Mint, YNAB) use OAuth to read transaction data without storing bank credentials.

  4. CI/CD integration — GitHub Actions accessing a cloud provider’s API uses OAuth client credentials for automated deployments.

  5. Smart home devices — A smart speaker accessing your calendar or music playlists uses OAuth with scoped permissions.

FAQ

What is the difference between OAuth 2.0 and OpenID Connect (OIDC)? |
OAuth 2.0 is for authorization (what can you access?). OpenID Connect is an identity layer on top of OAuth 2.0 for authentication (who are you?). OIDC adds an ID token (a JWT containing user identity info).
Is OAuth 2.0 an authentication protocol? |
No, OAuth 2.0 is an authorization framework. It grants access to resources. However, it is commonly used for authentication by combining it with OpenID Connect or by querying the userinfo endpoint.
What is a “scope” in OAuth? |
A scope is a permission granularity — a specific action the app is requesting. For example, read:email or write:posts. The user sees these scopes on the consent screen and can choose to grant or deny.
How do I revoke an application’s OAuth access? |
Users can revoke access from the service provider’s security settings page (e.g., Google Account → Third-party apps). Revoking invalidates the refresh token. Most providers also have a token revocation endpoint.
What happens when an access token expires? |
The API returns 401 Unauthorized. The app uses the refresh token to obtain a new access token without user interaction. If the refresh token is also expired or revoked, the user must re-authorize.

Related Terms

What is a JWT — What is an API — What is a REST API — What is a Microservice

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro