SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
  • Rate Limiting
  • Authentication vs Authorization
  • Session vs Token Based Auth
  • JWT
  • OAuth / OAuth2
  • Single Sign-On (SSO)
  • API Keys
  • OpenID Connect (OIDC)
  • CSRF
  • Input Validation
  • mTLS and Request Signing (HMAC)
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/APIs and Communication/API Security

OAuth / OAuth2

Let an app use your account safely, without ever giving it your password.

⏱ 15 min readIntermediateMust KnowInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

OAuth 2.0 lets an app use your account at another service, with limited permission, without ever seeing your password.

  • You approve on a consent screen. The app gets an access token, not your password.
  • The token has scopes (what it may do) and an expiry.
  • OAuth is about authorization (access). OpenID Connect (OIDC) adds login (who you are) on top of it.

02Concept: What is it?

Old way: an app asks, “Give me your email and password for that service.” That is dangerous. The app could do anything, and you could only stop it by changing your password. OAuth fixes this with a delegated pass.

The four roles

🧑Resource owner
You, the user who owns the data.
🖨️Client
The app that wants access (for example a photo printing app).
🔐Authorization server
Logs you in, asks for consent and issues tokens.
📸Resource server
The API that holds your data and checks the token.
The big picture
🧑You
→↓1. allow it
🔐Auth server
→↓2. token
🖨️App
→↓3. call API with token
📸API
Your password goes only to the authorization server.

03Real-Life Example

🍵The Valet Key
A car has a master key and a valet key. The valet key can start the car and park it, but cannot open the boot or the glove box. You hand over the valet key, not the master key. And you can take the valet key back.
Valet key
OAuth
Master key
Your password
Valet key
Access token
What the valet key can do
Scopes
Key expires at the end of the night
Token expiry
You can take the key back
Revoke access
The hotel desk that gives the key
Authorization server

04Why Do We Need It?

🔒No password sharing
Apps never see your password.
🎚️Limited access
Give “read photos”, not “delete everything”.
⏱️Short life
Access tokens expire quickly.
🚫Easy to revoke
Remove one app without changing your password.
🤝Open standard
Works the same across many providers.
OAuth moves the trust from “here is my password” to “here is a small, limited, cancellable pass”.

05Where Do We Use It?

🔑“Sign in with …” buttons
Use OpenID Connect, which is built on OAuth 2.0.
📅Calendar, email and file apps
Third-party tools read your data with scopes.
💳Open banking style APIs
A money app reads balances only if you consent.
🤖Machine to machine
Services call each other using client credentials.
📱Mobile apps
Log in through the system browser using the code flow with PKCE.

06Types / Parts / How It Works

Grant types (the ways to get a token)

GrantUsed forStatus
Authorization code + PKCEWeb apps, mobile apps and single-page apps with a userThe recommended one for user logins
Client credentialsService to service, no user involvedGood and common
Refresh tokenGet a new access token without asking the user againCommon companion
Device codeTVs and devices with no keyboard: type a code on your phoneGood for that case
ImplicitOld single-page apps: token comes straight back in the URLDiscouraged. Use code + PKCE
Resource owner passwordApp collects your password and sends it to the serverDiscouraged. It defeats the purpose of OAuth
💡What is PKCE?
PKCE (said “pixy”) protects the authorization code. The app makes a secret (code verifier) and sends only its hash (code challenge) at the start. At the end it must show the original secret. A thief who steals the code cannot use it.

OAuth vs OpenID Connect

OAuth 2.0
Access (authorization)
  • “This app may read the user's photos”
  • Gives an access token
  • Does not say who the user is
OpenID Connect (OIDC)
Login (authentication)
  • “The user is Asha, email asha@…”
  • Adds an ID token (a JWT) and a userinfo endpoint
  • Runs on top of the OAuth code flow with the scope “openid”
VisualizerOAuth authorization code flowTick the scopes on the consent screen, then press Next through each step.
Consent screen: what will you allow the Print app to do?
🧑Userresource owner
→↓clicks Connect
🖨️Print appclient
Step 1 of 7
1. The user clicks “Connect to PhotoBox”
A printing app (the client) wants to read photos the user stored at PhotoBox. The user does not want to give the printing app their PhotoBox password.
Your ticks change the access token in steps 5 and 6. The password is typed only into the auth server, never into the app. This is the authorization code flow with PKCE, the usual choice for web and mobile apps.

07How to Use It / Steps / Implementation

Authorization code flow with PKCE, step by step

  1. 1
    Register the app
    Get a client_id, and set an exact redirect_uri.
  2. 2
    Send the user to the auth server
    With client_id, redirect_uri, scope, a random state and a PKCE code_challenge.
  3. 3
    User logs in and gives consent
    On the auth server's own page.
  4. 4
    Auth server redirects back with a code
    The app checks that state matches the one it sent (this blocks CSRF).
  5. 5
    App exchanges the code for tokens
    A direct call to the token endpoint, with the code_verifier.
  6. 6
    Call the API
    Authorization: Bearer <access_token>. The API checks the token and scopes.
  7. 7
    Refresh when needed
    Use the refresh token to get a new access token.

Client credentials (no user)

🖥️Billing serviceclient_id + secret
→↓get a token
🔐Auth server
→↓access token
📊Reports API

08Key Terms to Know

TermMeaning in easy words
Access tokenA short-lived pass used to call an API
Refresh tokenA long-lived pass used only to get new access tokens
ScopeA named permission, like photos.read
ClientThe app asking for access
Redirect URIThe exact address the user is sent back to after consent
Authorization codeA one-time code swapped for tokens
PKCEExtra proof that the app that started the flow also finishes it
stateA random value that stops cross-site request forgery in the flow
Consent screenThe page where the user approves the permissions
OIDCOpenID Connect: login on top of OAuth
ID tokenA JWT from OIDC that says who the user is

09Pros, Cons and Trade-offs

✅ Pros
  • Apps never see the password
  • Limited, clear permissions (scopes)
  • Tokens expire and can be revoked
  • A standard supported almost everywhere
  • Works for users and for machines
⚠️ Cons
  • Many parts and many options, so it is easy to get wrong
  • Needs an authorization server
  • Redirects are confusing to debug
  • Tokens still need safe storage
  • OAuth alone is not login. You need OIDC for identity

Trade-offs

ChoiceWe gainWe lose
Run your own auth serverFull controlYou must keep it secure and running
Use a hosted identity providerLess work, proven securityCost and a dependency
Broad scopesFewer consent screensMore damage if a token leaks
Long refresh tokensFewer loginsBigger risk if stolen

10Common Problems and Mistakes

Common mistakes

  1. Using OAuth as if it were login. An access token does not say who the user is. Use OIDC.
  2. Using the implicit or password grant in new apps. Use code + PKCE.
  3. Loose redirect_uri checks. An attacker can steal the code. Match the URI exactly.
  4. Skipping the state check. Opens the door to CSRF.
  5. Putting a client secret in a mobile or browser app. It is not secret there. Use PKCE and public clients.
  6. Asking for too many scopes. Ask for the least you need.
  7. Leaking tokens in URLs or logs.
🪤Consent phishing
A fake app asks for wide scopes and the user clicks Allow. Review apps you approved.
🕳️Open redirect
A loose redirect lets the code flow to an attacker.
🧳Token theft
A stolen bearer token works for anyone until it expires.

11Real-World Examples

🔵“Continue with …” buttons
Most big account providers offer OAuth and OpenID Connect sign-in.
📸Printing and editing apps
Read your photos with a read-only scope.
💬Chat and workflow tools
Install apps into a workspace and approve scopes.
🐙Developer platforms
Third-party tools get access to your repositories with limited scopes.
☁️Cloud APIs
Service accounts use client-credentials style flows.
📝Note
Providers differ in small details (names of scopes, token life). Read the provider's docs.
Which flow for which app?
User signs in
🌐Web / mobile / SPA
↓
✅Code + PKCE
No user
🖥️Service to service
↓
✅Client credentials
No keyboard
📺Smart TV
↓
✅Device code
Recommended flow

12Related Topics to Read Next

JWT→

Access tokens and OIDC ID tokens are often JWTs.

Single Sign-On (SSO)→

SSO often uses OIDC (built on OAuth) or SAML.

Authentication vs Authorization→

OAuth is about authorization. OIDC adds authentication.

Session vs Token Based Auth→

OAuth gives you tokens to keep a user signed in.

HTTP / HTTPS→

Every step must run over HTTPS.

Rate Limiting→

Token and login endpoints need limits too.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • ✔What: delegated access with a limited token, without sharing the password.
  • ✔Roles: user, client, auth server, resource server.
  • ✔Best flow for users: authorization code + PKCE.
  • ✔No user: client credentials.
  • ✔Avoid: implicit and password grants.
  • ✔Tokens: short access token, longer refresh token, scopes limit power.
  • ✔Login? Use OpenID Connect (ID token), not plain OAuth.
  • ✔Checks: exact redirect_uri, state, least scopes, HTTPS.
  • ✔One line: “OAuth hands out a valet key, not the master key.”
← Previous
JWT
Next →
Single Sign-On (SSO)