Every time you click “Sign in with Google”, let a calendar app read your events, or allow a CI tool to push to your GitHub repo, OAuth 2.0 is doing the work. It is the standard that lets one application act on your behalf in another without ever seeing your password.
It is also one of the most misunderstood standards in software. This note is a compact tour: the idea, the players, the main flow, real code, and the mistakes to avoid.
The one-sentence definition
OAuth 2.0 is a framework for delegated authorization: it lets a user grant an application limited, revocable access to their data on another service, using a token instead of their password.
Two words matter there: limited (scopes) and revocable (tokens can expire or be cancelled).
The valet-key analogy
When you hand your car to a hotel valet, you give them a valet key. It starts the engine and opens the driver’s door, but it cannot open the trunk or the glove box. You never hand over your master key.
OAuth is the valet key:
- Master key = your username and password (full power, never shared).
- Valet key = an access token (limited power, short-lived, revocable).
The four roles
Every OAuth conversation has the same four actors. Learn these names and every diagram in the spec becomes readable.
Scopes are the permissions the client asks for, such as calendar.readonly or orders:read. The user sees them on the consent screen, and the token carries only what was approved.
The main event: Authorization Code flow
This is the flow you should use for almost everything today: web apps, mobile apps, and single-page apps (with PKCE, covered next). The key trick is that the browser only ever carries a short-lived code; the real token is exchanged server-to-server.
Why the extra “code” hop?
Because the front channel (browser URL, history, referrer headers, logs) is leaky. If tokens travelled there, anyone watching could steal them. A one-time code is useless without the client’s own credentials or PKCE verifier, so a stolen code is not a stolen session.
PKCE: protecting public clients
Mobile apps and SPAs cannot keep a client_secret safe, because anyone can unpack the app. PKCE (Proof Key for Code Exchange, pronounced “pixie”) fixes this with a per-request secret: the client invents a random string, sends only its hash up front, and reveals the original later to prove it is the same client.
Show me the code
Here is the whole flow in Laravel, using only the HTTP client so every step stays visible. (In production you would likely reach for Laravel Socialite or Passport, shown below.)
Step 1 — redirect to the authorization server
// routes/web.php
use Illuminate\Support\Str;
Route::get('/auth/redirect', function () {
$verifier = Str::random(64);
$challenge = rtrim(strtr(base64_encode(hash('sha256', $verifier, true)), '+/', '-_'), '=');
$state = Str::random(40);
session(['pkce_verifier' => $verifier, 'oauth_state' => $state]);
$query = http_build_query([
'response_type' => 'code',
'client_id' => config('services.provider.client_id'),
'redirect_uri' => route('oauth.callback'),
'scope' => 'profile email',
'state' => $state, // CSRF protection
'code_challenge' => $challenge, // PKCE
'code_challenge_method' => 'S256',
]);
return redirect('https://auth.example.com/authorize?' . $query);
});
Step 2 — handle the callback and swap the code for tokens
Route::get('/auth/callback', function (Request $request) {
// 1. Reject forged or replayed callbacks
abort_unless(
hash_equals((string) session()->pull('oauth_state'), (string) $request->query('state')),
403, 'Invalid state'
);
// 2. Server-to-server token exchange
$tokens = Http::asForm()->post('https://auth.example.com/token', [
'grant_type' => 'authorization_code',
'code' => $request->query('code'),
'redirect_uri' => route('oauth.callback'),
'client_id' => config('services.provider.client_id'),
'client_secret' => config('services.provider.client_secret'),
'code_verifier' => session()->pull('pkce_verifier'),
])->throw()->json();
// 3. Call the API with the access token
$profile = Http::withToken($tokens['access_token'])
->get('https://api.example.com/me')
->throw()
->json();
// ...log the user in, store tokens encrypted
});
The token response looks like this:
{
"token_type": "Bearer",
"access_token": "eyJhbGciOiJSUzI1NiIs...",
"expires_in": 900,
"refresh_token": "def50200a1b2c3...",
"scope": "profile email"
}
The shortcut: Laravel Socialite
// redirect
return Socialite::driver('github')->redirect();
// callback
$user = Socialite::driver('github')->user();
$user->getEmail(); // handles state, code exchange and profile fetch
The other side: protecting your own API with scopes
If you are the resource server, every endpoint should check that the token carries the right scope. With Laravel Passport:
Route::middleware(['auth:api', 'scope:orders:read'])
->get('/orders', [OrderController::class, 'index']);
Route::middleware(['auth:api', 'scope:orders:write'])
->post('/orders', [OrderController::class, 'store']);
A token with only orders:read gets a 403 on the POST. That is the valet key in action.
Token lifecycle: access vs refresh
Access tokens are deliberately short-lived, because they are sent on every request and are the most exposed. A refresh token lets the client quietly get a new one without bothering the user.
$tokens = Http::asForm()->post('https://auth.example.com/token', [
'grant_type' => 'refresh_token',
'refresh_token' => $stored->refresh_token,
'client_id' => config('services.provider.client_id'),
'client_secret' => config('services.provider.client_secret'),
])->throw()->json();
// Save BOTH new values: the refresh token has rotated
$stored->update([
'access_token' => encrypt($tokens['access_token']),
'refresh_token' => encrypt($tokens['refresh_token']),
'expires_at' => now()->addSeconds($tokens['expires_in']),
]);
Which grant type should I use?
OAuth defines several “grants” (ways to obtain a token). Picking the right one is mostly a lookup.
| Situation | Use | Notes |
|---|---|---|
| Web app with a backend, user signs in | Authorization Code + PKCE | The default answer. |
| SPA or mobile app | Authorization Code + PKCE | No client secret; PKCE is essential. |
| Server-to-server, no user involved | Client Credentials | Cron jobs, microservices, machine identity. |
| TV or CLI with no browser | Device Code | User approves on a second device. |
| Renewing an expired access token | Refresh Token | Not a login method; a renewal method. |
| Deprecated | Tokens in URLs. Replaced by Code + PKCE. | |
| Deprecated | Client handles the raw password, defeating OAuth’s purpose. |
Machine-to-machine in one call:
curl -X POST https://auth.example.com/token \
-d grant_type=client_credentials \
-d client_id=billing-service \
-d client_secret=*** \
-d scope=invoices:write
OAuth is not login: meet OpenID Connect
A very common misconception: OAuth 2.0 answers “what may this app do?”, not “who is this user?”
An access token says an app may read a calendar. It does not promise to tell the app who the user is. OpenID Connect (OIDC) is a thin identity layer on top of OAuth 2.0 that adds an ID token (a signed JWT with the user’s identity) and a /userinfo endpoint.
| OAuth 2.0 | OpenID Connect | |
|---|---|---|
| Purpose | Authorization (access) | Authentication (identity) |
| Key artifact | Access token | ID token (JWT) |
| Question answered | “What can this app do?” | “Who is this user?” |
| Add this scope | calendar.readonly |
openid profile email |
“Sign in with Google” is OIDC running on OAuth 2.0. If you only need to log users in, request the openid scope and validate the ID token.
Mistakes that cause real breaches
| Mistake | Why it hurts | Fix |
|---|---|---|
Skipping the state parameter |
Attacker forces a victim to link the attacker’s account (login CSRF). | Random state per request, verified in the callback. |
Loose redirect_uri matching |
Codes and tokens are sent to an attacker’s domain. | Register exact URIs. No wildcards, no open redirects. |
Tokens in localStorage |
Any XSS steals them. | Prefer HttpOnly session cookies via a backend (BFF pattern). |
| Using the Implicit or Password grant | Token exposure, password handling. | Authorization Code + PKCE. |
| Over-broad scopes | A stolen token can do everything. | Least privilege: request only what you need. |
| Long-lived access tokens | Large theft window. | 5–15 minutes, plus refresh token rotation. |
| Treating an access token as proof of identity | Token substitution attacks. | Use OIDC and validate the ID token’s aud, iss and exp. |
| Logging tokens or putting them in URLs | Tokens leak into logs and analytics. | Send in the Authorization header only, and redact logs. |
A seven-point checklist
- Use Authorization Code + PKCE for every user-facing flow; avoid Implicit and Password grants.
- Always send and verify
state, and register exactredirect_urivalues. - Request the smallest scopes that make the feature work, and enforce them on every API endpoint.
- Keep access tokens short-lived (minutes) and rotate refresh tokens.
- Store tokens server-side and encrypted; never in URLs, logs, or
localStorage. - Use OpenID Connect when you need to know who the user is, and validate the ID token.
- Don’t hand-roll it. Prefer a battle-tested library or provider (Socialite, Passport, Keycloak, Auth0, Cognito) over writing token logic yourself.
Conclusion
OAuth 2.0 is the valet key of the internet: a way to give an application just enough access, for just long enough, without ever handing over the master key. Remember the four roles (owner, client, authorization server, resource server), remember that the Authorization Code flow with PKCE is the default answer, and remember that access tokens are short-lived while refresh tokens quietly keep users signed in. Add OpenID Connect when you need identity, enforce scopes on your own APIs, and most OAuth-related breaches become things that happen to other teams.