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

Authentication vs Authorization

Who are you? And what are you allowed to do?

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

01Quick Summary

Authentication answers “Who are you?” Authorization answers “What are you allowed to do?”

  • Authentication always comes first. You cannot decide what someone may do before you know who they are.
  • Not logged in: 401. Logged in but not allowed: 403.
  • Short names: AuthN (authentication) and AuthZ (authorization).

02Concept: What is it?

Authentication (AuthN)
Who are you?
  • Proves your identity
  • Password, fingerprint, one-time code, security key
  • Result: “you are Asha”
  • Fails with 401 Unauthorized
Authorization (AuthZ)
What may you do?
  • Checks your permissions
  • Roles, rules and policies
  • Result: “Asha may read reports, but not delete users”
  • Fails with 403 Forbidden
Two checks, in this order
🧑Request
→↓
🪪1. Authenticatewho is this?
→↓known user
📋2. Authorizeis it allowed?
→↓yes
✅Do the action
⚠️A confusing name
HTTP status 401 is called “Unauthorized”, but it really means “not authenticated”. The status for “not authorized” is 403 Forbidden.

03Real-Life Example

🍵The Office Building
At the gate, the guard checks your ID card (authentication). Inside, your card opens only some doors. The accounts floor opens for finance staff, not for visitors (authorization).
Office building
Software
Showing your ID at the gate
Logging in (authentication)
Guard turns you away: no ID
401 Unauthorized
Door that opens only for finance
A protected API route
Card that does not open that door
403 Forbidden
Job title on the card (visitor, staff, manager)
Role (RBAC)
Card plus a code from your phone
Multi-factor authentication (MFA)

04Why Do We Need It?

🔒Protect private data
Only the owner should see their messages, orders and money.
🧑‍🤝‍🧑Different users, different powers
Customer, support agent and admin should not see the same things.
🧾Know who did what
Audit logs need a real identity behind every action.
⚖️Rules and law
Health, finance and privacy laws need access control.
🛡️Limit the damage
If one account is stolen, a small set of permissions means a small loss.
Authentication stops strangers. Authorization stops insiders from going where they should not.

05Where Do We Use It?

🏦Banking apps
Strong login, then rules on who can move how much money.
🛒E-commerce
You see your orders, not other people's. Sellers see their own shop.
🏥Health records
Doctors see their patients only.
💼Company tools
Managers approve; employees request.
☁️Cloud consoles
Fine-grained roles decide who can start or delete servers.
🔌APIs
Every API call is checked, from apps and from other services.

Where the checks happen

🚪API gatewayauthentication, coarse rules
🖥️Service codedetailed authorization
🗄️Databaserow-level rules (sometimes)

06Types / Parts / How It Works

Ways to prove who you are (authentication)

MethodHow it worksUse it forWatch out for
PasswordSomething you knowNormal loginsWeak or reused passwords. Always store them hashed with a slow, salted algorithm, never in plain text.
API keyA long secret string sent with each callServer-to-server and developer APIsIdentifies an app, not a person. If leaked, anyone can use it. Rotate keys.
Basic authUsername:password in a header, base64 encoded (not encrypted)Quick internal toolsOnly safe over HTTPS. Sends the password every time.
Bearer tokenA token in the Authorization header: whoever holds it is trustedModern APIs (JWT, OAuth access tokens)Treat the token like a password. Keep it short-lived.
Cookie sessionA session id stored in a cookieWebsitesSet HttpOnly, Secure and SameSite flags.
MFAPassword plus another factor (phone code, app, security key)Anything importantSMS codes can be hijacked. Apps and keys are stronger.
Three kinds of proof (factors)
🧠Something you knowpassword, PIN
📱Something you havephone, security key
👆Something you arefingerprint, face
MFA means using two or more different kinds together.

Ways to decide what you may do (authorization)

ModelIdeaExample
RBAC (role based)Give permissions to roles; give users roles.Role “support” can read tickets and refund up to ₹500.
ABAC (attribute based)Decide using attributes of the user, the data and the situation.A doctor can read a record only if the patient is in their ward and it is working hours.
ACL (access control list)A list on each object saying who can do what.A shared document: Asha can edit, Ben can view.
ScopesPermissions written inside a token (see OAuth).read:photos but not delete:photos
VisualizerThe security guardLog in or not, then try each door. Watch for 401 and 403.
1. Who is at the door?
🧍Unknown visitorno ID shown
→↓authentication
💂Guardchecks ID, then the list
→↓authorization
🚪Doorsresources
2. Try to open a door (what may you do?)
200 OK
0
401
0
who are you?
403
0
not allowed
Pick who is at the door, optionally log in, then click a door. Try “Not logged in” on My profile (401). Then log in as Asha and try Sales reports (403).

07How to Use It / Steps / Implementation

Steps for a safe design

  1. 1
    Authenticate at the edge
    Check the password, token or key before anything else. Always use HTTPS.
  2. 2
    Attach the identity to the request
    After login, the server knows the user id and roles for the rest of the request.
  3. 3
    Authorize on every request
    Check the permission on the server for every action. Never trust a button that is merely hidden in the UI.
  4. 4
    Check the object too, not only the role
    “Can this user read order 42?” Skipping this causes the well-known bug where changing an id in the URL shows someone else's data (IDOR).
  5. 5
    Deny by default
    If no rule allows it, refuse.
  6. 6
    Give the least access needed
    Small permissions, short-lived tokens, rotate keys.
  7. 7
    Log and monitor
    Record logins, failures and permission denials.

Which status code?

SituationCodeMeaning
No credentials, bad password, expired token401I do not know who you are. Log in (and send a WWW-Authenticate hint).
Logged in, but the role is not enough403I know who you are, and the answer is no.
Too many tries429Slow down (see Rate Limiting).
💡Hide that it exists?
Sometimes a 404 is used instead of 403, so outsiders cannot even learn that a private item exists.

08Key Terms to Know

TermMeaning in easy words
IdentityWho someone is (a user id, an email, an app id)
CredentialThe proof of identity: password, token, key, certificate
Authentication (AuthN)Checking who you are
Authorization (AuthZ)Checking what you may do
RoleA named bundle of permissions, like “admin”
PermissionOne allowed action, like “delete user”
RBACRole-based access control
MFA / 2FAUsing two or more kinds of proof
Principle of least privilegeGive only the access that is really needed
Bearer tokenA token that grants access to whoever carries it
HashingA one-way scramble used to store passwords safely (with salt)

09Pros, Cons and Trade-offs

✅ Pros
  • Keeps private data private
  • Clear audit trail
  • Limits damage from stolen accounts
  • Lets one system serve many kinds of users
⚠️ Cons
  • More work in every service
  • Login steps can annoy users
  • Permission rules can become messy over time
  • A bug here is a security hole
  • Needs careful secret and token handling

Trade-offs

ChoiceWe gainWe lose
Strong MFAMuch harder to break inExtra step for the user, recovery is harder
Short token lifeStolen tokens stop working soonMore refreshes and logins
Fine-grained permissionsTight controlHarder to manage and to explain
Check at the gateway onlyOne place, simpleServices behind it may trust too much

10Common Problems and Mistakes

Common mistakes

  1. Mixing up 401 and 403. Not known = 401. Known but not allowed = 403.
  2. Hiding a button and calling it security. Anyone can call the API directly. Check on the server.
  3. Checking the role but not the object (IDOR). User 7 changes /orders/42 to /orders/43 and sees a stranger's order.
  4. Storing passwords in plain text, or with a fast hash. Use a slow, salted password hash such as bcrypt, scrypt or Argon2.
  5. Putting secrets or API keys in front-end code or in a git repo.
  6. Allow by default. A new route added without a rule becomes public.
  7. Never expiring tokens or sessions.
  8. Writing your own crypto. Use trusted libraries and standards.
🔑Credential stuffing
Attackers try leaked passwords from other sites. Use MFA and rate limits.
🎣Phishing
A fake page steals the password. Security keys and passkeys resist this.
📈Privilege creep
People collect permissions over the years. Review them often.
🔓Broken access control
A top web security risk in the OWASP list. Test it.

11Real-World Examples

🏦Net banking
Password plus a one-time code, then limits on the amount you may send.
☁️Cloud providers
Detailed roles and policies decide who may touch which resource.
🐙Code hosting sites
Anyone can read public repos; only members can push; only owners can delete.
📺Streaming services
Your login shows your profile; your plan decides which features you get.
📱Phones
Fingerprint or face to unlock (authentication). Apps ask for camera or location (authorization).
🛒Marketplaces
Buyers, sellers and admins have different pages and powers.
One request, two decisions
🧑Asharole: user
→↓GET /reports
🪪AuthN✓ known
→↓
📋AuthZ✕ needs admin
→↓403
⛔Forbidden
User Passed Blocked
Asha is known (authenticated), but a user may not read the sales reports (authorization fails).
Remember
Authentication ≠ Authorization. A valid login is not a permission slip.

12Related Topics to Read Next

Session vs Token Based Auth→

Two ways to remember that someone has logged in.

JWT→

A popular token format that carries identity and roles.

OAuth / OAuth2→

Lets one app act for you at another service, with limited permissions.

Single Sign-On (SSO)→

Authenticate once and use many apps.

Rate Limiting→

Stops password guessing and abuse by slowing callers down.

HTTP / HTTPS→

Credentials must always travel over HTTPS.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • ✔AuthN: who are you? AuthZ: what may you do?
  • ✔Order: authenticate first, then authorize.
  • ✔Codes: 401 = not known, 403 = known but not allowed.
  • ✔Credentials: password, API key, bearer token, cookie session, MFA.
  • ✔Access models: RBAC (roles), ABAC (attributes), ACL, scopes.
  • ✔Always: HTTPS, deny by default, least privilege, check on the server.
  • ✔Classic bug: role checked but the object not (IDOR).
  • ✔Passwords: salted, slow hash. Never plain text.
  • ✔One line: “First prove who you are, then show you are allowed.”
← Previous
Rate Limiting
Next →
Session vs Token Based Auth