What is OAuth 2.0 — Simple Explanation with Examples
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
| Role | Description | Example |
|---|---|---|
| Resource Owner | The user who owns the data | You |
| Client | The application requesting access | A photo printing app |
| Authorization Server | Issues tokens after authentication | Google’s OAuth server |
| Resource Server | Hosts the protected data, validates tokens | Google 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
| Token | Purpose | Lifetime | Can be revoked? |
|---|---|---|---|
| Access Token | Sent with every API call to authorize access | Short-lived (15 min–1 hour) | Typically not |
| Refresh Token | Exchanged for a new access token without user re-auth | Long-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
- Always use HTTPS — Tokens in transit must be encrypted.
- Use short-lived access tokens — Limits damage if a token leaks.
- Use PKCE for mobile/SPA — Protects against authorization code interception.
- Validate redirect URIs — The server must only redirect to registered URIs to prevent open redirect attacks.
- Use state parameter — A random string sent with the auth request and verified on return prevents CSRF attacks.
- Never log tokens — Access and refresh tokens should never appear in logs or error messages.
Common Use Cases
Social login — “Sign in with Google/Facebook/GitHub/Twitter” uses OAuth 2.0 to authenticate users without handling passwords.
API access delegation — A SaaS app integrating with a user’s Google Drive or Dropbox uses OAuth to request specific file access scopes.
Mobile banking integrations — Budgeting apps (Mint, YNAB) use OAuth to read transaction data without storing bank credentials.
CI/CD integration — GitHub Actions accessing a cloud provider’s API uses OAuth client credentials for automated deployments.
Smart home devices — A smart speaker accessing your calendar or music playlists uses OAuth with scoped permissions.
FAQ
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