OAuth From Zero

A beginner's guide to OAuth 2.0

Let an app use your account without giving it your password.

OAuth is what runs behind "Connect your account" and "Sign in with" buttons. This guide takes you from zero to reading a real authorization request. You will step through the full flow, build a request, decode a token and finish with a short quiz.

8 chapters. About 20 minutes. No code needed.

This is a real-looking OAuth request. By chapter 4 you will be able to read every part of it.

https://auth.snapshelf.example/authorize
?response_type=code
&client_id=printly-web-4821
&redirect_uri=https%3A%2F%2Fprintly.example%2Fcallback
&scope=photos.read%20profile
&state=af0ifjsldkj
&code_challenge=E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM
&code_challenge_method=S256
Chapter 1

The problem: handing over your password

Imagine Printly is a service that prints photos, and your photos live at Snapshelf. Printly needs to read them. The old way to make that work was to give Printly your Snapshelf email and password.

That works, and it is a bad deal. Printly can now do everything you can do, including deleting every photo or changing your password. It keeps that power until you change the password, which also breaks every other app you trusted. Snapshelf cannot tell Printly's requests from yours.

OAuth replaces the password with a pass. Snapshelf gives Printly a token that opens only the doors you approved, expires on its own, and can be cancelled without touching anything else. Think of a valet key. It starts the car, and it will not open the trunk or the glovebox.

Sharing your passwordUsing OAuth
What the app can doEverything you can doOnly what you approved
How long it lastsUntil you change your passwordMinutes to hours, then renewed or ended
Cutting it offChange your password and break every other appRevoke that one app
Who sees your passwordEvery app you shared it withOnly Snapshelf's own login page
Keep this straight

OAuth handles authorization, which is what an app may do for you. Proving who you are is a different job called authentication. Chapter 6 covers the layer that adds it.

Chapter 2

Four parts in every conversation

The spec gives each part a formal name. You will see these names in documentation, so each card shows both.

Resource owner

You

Own the photos and decide which apps may use them.

Client

Printly

The app that wants access. It never sees your password.

Authorization server

Snapshelf login and consent

Checks who you are, asks what you allow, and issues tokens.

Resource server

Snapshelf photo API

Holds the photos. Answers a request only when it carries a valid token.

Small services often run the authorization server and the resource server together. They are still two separate jobs, and the flow treats them that way.

One thing happens before any of this. Printly's developer registers the app with Snapshelf and receives a client_id. The developer also lists the exact URLs Snapshelf may send users back to. That list matters in chapter 4.

Chapter 3

The flow, one step at a time

This is the Authorization Code flow with PKCE. It is the one you will use for almost everything. Use the buttons or the arrow keys to move through it.

Dashed arrows pass through your browser. Solid arrows are direct connections.

The front channel

Steps 2 and 4 travel through your browser. Anything in a redirect URL lands in history, logs and extensions, so it can leak. That is why this channel only carries a short-lived code that cannot do anything alone.

The back channel

Steps 5 to 8 go directly between servers over HTTPS. Nothing in your browser can see them. Tokens only ever travel here.

Chapter 4

Reading the authorization request

Step 2 sent your browser to Snapshelf with a long URL. Tap any piece of it below to see what it does and why it is there.

The odd characters such as %3A%2F%2F are punctuation made safe for URLs. %20 is a space.

Scopes decide what the consent screen says

Tick some boxes. The scope part of the URL changes, and so does the screen Snapshelf shows you in step 3.

Permissions Printly asks for

Ask for the least you need. A leaked token can only do what its scopes allow.

Try PKCE

PKCE is pronounced "pixie". Printly invents a secret called the code verifier. It sends only the hash of that secret in step 2 and reveals the secret itself in step 5. Someone who steals the code from the redirect still lacks the verifier. Edit the verifier and watch the challenge change.

Chapter 5

Access tokens and refresh tokens

Step 6 returned two tokens. They have different jobs and different risks.

Access token

The pass

Used for
Calling the API
Lifetime
Short, often 5 to 60 minutes
Sent to
The resource server, in the Authorization header
If it leaks
Works until it expires, within its scopes
Refresh token

The renewal slip

Used for
Getting new access tokens without asking you again
Lifetime
Days to months, or until revoked
Sent to
Only the authorization server's token endpoint
If it leaks
Serious, so store it carefully and rotate it

When the access token expires, the API answers 401. Printly then asks the token endpoint for a new one:

POST /token HTTP/1.1
Host: auth.snapshelf.example
Content-Type: application/x-www-form-urlencoded

grant_type=refresh_token
&refresh_token=tGzv3JOkF0XG5Qx2TlKWIA
&client_id=printly-web-4821

This design pays off when you change your mind. Open Snapshelf's connected apps page and remove Printly. Snapshelf invalidates Printly's tokens, and nothing else in your account changes.

Many access tokens are opaque strings. Client apps should treat them as opaque and never try to read them. Only the API needs to understand what is inside.

Chapter 6

Logging in with OpenID Connect

Now suppose Printly also wants a "Sign in with Snapshelf" button. An access token cannot serve as proof of who you are. It is written for the API, and it tells the app very little about you.

OpenID Connect, usually shortened to OIDC, is a thin layer on top of OAuth that fixes this. Add the scope openid to the request and the token response includes an ID token. That is a signed JSON Web Token (JWT) that says who just logged in.

A JWT is three pieces joined by dots. Here is one, decoded in your browser.

Header
Payload

The signature here is a placeholder, and the check is simulated. Real servers verify it with the issuer's public key.

Anyone can read a JWT. The signature does not hide the contents. It proves nobody changed them after Snapshelf signed it.

Before trusting an ID token, an app checks that:

  • the signature is valid for the issuer's published key
  • iss is the server you expected
  • aud is your own client_id
  • exp is still in the future
  • nonce matches the one you sent in the request
Chapter 7

Which flow fits your app?

OAuth defines several flows, called grant types. Pick the kind of app you are building.

Skip these

Two older flows are discouraged by current security guidance. The implicit flow returned tokens in the URL. The password flow made apps collect your password, which brings back the original problem. The OAuth 2.1 draft drops both.

Chapter 8

Seven common mistakes

Most OAuth security problems come from skipping one of the small checks you have already seen.

  • Skipping state

    An attacker can feed your app a callback for a login they started.

    Do this. Generate a random value per request, store it in the session, and compare it on return.

  • Loose redirect URIs

    Wildcards and prefix matches let attackers steer codes to their own pages.

    Do this. Register exact URLs and require an exact string match.

  • Tokens in URLs

    URLs end up in browser history, server logs and Referer headers.

    Do this. Send access tokens only in the Authorization header.

  • Secrets in front-end code

    Anything shipped to a browser or phone can be extracted, so a secret there is public.

    Do this. Treat those apps as public clients. Use PKCE and keep secrets on a server.

  • Using an access token as login

    It says an app may call an API. It does not say who is using the app.

    Do this. Use OpenID Connect and validate the ID token.

  • Asking for every scope

    Long consent screens scare users, and a leaked token can do more.

    Do this. Request the minimum, and ask for more when a feature needs it.

  • Long-lived access tokens

    A leaked token works until it expires.

    Do this. Keep access tokens short and rotate refresh tokens.

Check yourself

Six questions

0 of 6 answered
Reference

Glossary

Resource owner
The person who owns the data and grants access.
Client
The app asking for access.
Authorization server
Authenticates the user, collects consent and issues tokens.
Resource server
The API that holds the data and checks tokens.
Scope
A named permission, such as photos.read.
Consent
The screen where the user allows or denies the requested scopes.
Redirect URI
The pre-registered URL where the user returns after deciding.
Authorization code
A short-lived, single-use ticket traded for tokens.
Access token
The credential sent with API requests.
Refresh token
A long-lived credential used to get new access tokens.
Bearer token
A token that works for whoever holds it, so it must be protected.
ID token
An OpenID Connect JWT that says who logged in.
PKCE
A check that ties the code to the app that asked for it.
State
A random value that links the callback to the request that started it.
Public client
An app that cannot keep a secret, such as a mobile or single-page app.
Confidential client
An app with a server that can keep a client secret.
OIDC
OpenID Connect, the login layer built on OAuth 2.0.
Grant type
The name of a flow, such as authorization_code.

Keep reading