Security & Identity
OAuth 2.0 Explained: Roles, Grants, PKCE and Current Best Practice
Intermediate7 min readUpdated
OAuth 2.0 lets an application act on a user's behalf without ever seeing their password, and almost every mistake with it comes from misunderstanding what it delegates. This guide walks through the roles, the HTTP messages of the authorization code flow with PKCE, the other grants worth knowing, how scopes and consent work, and what the IETF's Security Best Current Practice removes from the original specification.
What you will learn
- Explain what OAuth 2.0 delegates and why it is authorization rather than authentication
- Trace the authorization code flow with PKCE message by message
- Choose the right grant for a browser app, a mobile app, a backend job or a television
- Use scopes, consent, refresh tokens, introspection and revocation correctly
- Apply RFC 9700 rules on redirect URIs, deprecated grants and sender-constrained tokens
OAuth 2.0 exists to answer a very specific question: how can an application call an API on your behalf without you handing it your password? Before OAuth, the honest answer was that you gave the application your credentials and hoped, which meant every integration held keys to your whole account and could never be revoked individually. OAuth replaces that with a token — narrow, expiring, revocable — issued after you approved a specific request at a site you already trust.
The framework is small but it is often misread. It is an authorization framework, not an authentication protocol; the specification deliberately says nothing about how the user proved who they are. Almost every serious OAuth problem in the wild comes from either forgetting that distinction or from implementing a flow that the ecosystem has since retired. This guide covers the roles, the flows worth using in 2026, how tokens behave, and the rules from RFC 9700 that supersede parts of the original RFC 6749.
The four roles
- The resource owner is the user who owns the data — usually a person, sometimes an organisation.
- The client is the application that wants access. It is confidential if it can keep a secret (a server-side web app) and public if it cannot (a mobile app, a browser app).
- The authorization server authenticates the resource owner, obtains consent and issues tokens. It publishes an authorization endpoint (front channel, browser) and a token endpoint (back channel, direct HTTPS).
- The resource server is the API that accepts the token and serves the data.
Two communication paths matter throughout. The front channel passes through the user's browser via redirects: it is visible, loggable and manipulable, so nothing secret may travel there. The back channel is a direct server-to-server HTTPS call, authenticated and private. The design of every OAuth flow is essentially a decision about which value goes down which channel.
Authorization code flow with PKCE, step by step
This is the flow to use for browser applications, mobile applications and server-rendered web applications alike. Proof Key for Code Exchange (RFC 7636) was originally a mobile fix; it is now mandatory for everyone.
The client first generates a high-entropy random string, the code verifier, and derives a code challenge from it by SHA-256 hashing and base64url encoding. Only the challenge goes through the browser.
code_verifier = 43-128 chars of unreserved randomness, e.g. "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"
code_challenge = BASE64URL( SHA256( code_verifier ) )
1. Authorization request. The client redirects the browser to the authorization endpoint.
GET /authorize?response_type=code
&client_id=s6BhdRkqt3
&redirect_uri=https%3A%2F%2Fapp.example.com%2Fcallback
&scope=orders.read%20orders.write
&state=af0ifjsldkj
&code_challenge=E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM
&code_challenge_method=S256 HTTP/1.1
Host: auth.example.com
The state parameter is an opaque value the client stores in its session and checks on return; it binds the response to the request and defeats cross-site request forgery against the redirect endpoint.
2. Authentication and consent. The authorization server authenticates the user however it likes — password plus a second factor, a passkey, an existing session — and shows a consent screen listing the requested scopes. None of this involves the client.
3. Redirect back with a code.
HTTP/1.1 302 Found
Location: https://app.example.com/callback?code=SplxlOBeZQQYbYS6WxSbIA&state=af0ifjsldkj
The authorization code is single-use, short-lived (seconds to a couple of minutes) and useless on its own.
4. Token request on the back channel. The client now proves it started the flow by sending the original verifier.
POST /token HTTP/1.1
Host: auth.example.com
Content-Type: application/x-www-form-urlencoded
Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW
grant_type=authorization_code
&code=SplxlOBeZQQYbYS6WxSbIA
&redirect_uri=https%3A%2F%2Fapp.example.com%2Fcallback
&code_verifier=dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk
5. Token response.
{
"access_token": "eyJhbGciOiJSUzI1NiIsImtpZCI6IjIwMjYtMDMifQ...",
"token_type": "Bearer",
"expires_in": 300,
"refresh_token": "8xLOxBtZp8",
"scope": "orders.read orders.write"
}
The authorization server recomputes SHA256(code_verifier) and compares it with the challenge it stored. An attacker who somehow intercepted the code in the front channel cannot redeem it, because the verifier never left the legitimate client.
6. Calling the API. The access token travels in the Authorization header as defined by RFC 6750, and the resource server validates it before doing anything else.
GET /orders/1042 HTTP/1.1
Host: api.example.com
Authorization: Bearer eyJhbGciOiJSUzI1NiIsImtpZCI6IjIwMjYtMDMifQ...
How that validation should be performed — signature checking, claim validation, key rotation — is the subject of securing REST APIs with JWT. If you need to inspect a token while debugging, a client-side JWT decoder shows the claims without sending it anywhere.
The other grants, and the ones that are gone
Client credentials is for machine-to-machine calls where there is no user at all: a nightly job, one service calling another. The client authenticates and receives a token representing itself.
POST /token HTTP/1.1
Host: auth.example.com
Content-Type: application/x-www-form-urlencoded
grant_type=client_credentials&scope=ledger.post
There is no refresh token here — the client simply asks again — and there must be no user-specific authorization logic attached to such a token, because it carries no user.
Device authorization grant (RFC 8628) covers input-constrained devices: a television, a printer, a command-line tool. The device asks for a code, displays a short user code and a URL, and polls the token endpoint while the user completes the flow on a phone or laptop.
POST /device_authorization HTTP/1.1
Host: auth.example.com
Content-Type: application/x-www-form-urlencoded
client_id=tv-app&scope=video.play
{
"device_code": "GmRhmhcxhwAzkoEqiMEg_DnyEysNkuNhszIySk9eS",
"user_code": "WDJB-MJHT",
"verification_uri": "https://auth.example.com/device",
"expires_in": 1800,
"interval": 5
}
Refresh token grant exchanges a refresh token for a new access token without user interaction. Public clients must use refresh token rotation: each use returns a new refresh token and invalidates the old one, and if an already-used token reappears the server revokes the whole chain, since that pattern means one copy was stolen.
Two grants from the original specification are now prohibited by RFC 9700. The implicit grant returned an access token directly in the URL fragment, where it leaked into browser history, referrers and any script on the page; the code flow with PKCE covers the same use case safely. The resource owner password credentials grant required the client to handle the user's password, which defeats the entire point of the framework and blocks multi-factor authentication and step-up. The consolidation of these rules is what the industry refers to as OAuth 2.1.
Scopes, consent and audience
A scope is a coarse label for a permission the client is asking for — orders.read, profile, payments.initiate. The authorization server decides which scopes a given client may request at all, the user consents to them, and the resource server enforces them. Three cautions:
- Scopes describe what the client may attempt, not what the user may do. A token with
orders.readstill requires the API to check that this user may read this order. Skipping that check is the most common OAuth-adjacent access-control bug. - Keep scopes few and meaningful. Hundreds of fine-grained scopes produce unreadable consent screens, and consent that nobody reads is not consent.
- Use the
audience(or a resource indicator) so a token minted for one API cannot be replayed against another. A token accepted everywhere turns a single compromised service into a full compromise.
For first-party clients, organisations often skip the consent screen; that is a policy decision the authorization server makes, not something the client may assume.
Token lifetime, introspection and revocation
Access tokens should be short-lived — minutes, not days — because they are bearer credentials: whoever holds one can use it. Refresh tokens are long-lived and therefore must be stored with care and bound to the client.
Tokens come in two shapes. A self-contained token (usually a signed JWT) can be validated offline by any resource server holding the issuer's public keys, which scales well but means revocation is not instant. An opaque token is a random handle the resource server must look up, which gives immediate revocation at the cost of a network call on every request; RFC 7662 introspection defines that lookup.
POST /introspect HTTP/1.1
Host: auth.example.com
Authorization: Basic cmVzb3VyY2Utc2VydmVyOnNlY3JldA==
Content-Type: application/x-www-form-urlencoded
token=mF_9.B5f-4.1JqM
{ "active": true, "scope": "orders.read", "client_id": "s6BhdRkqt3", "sub": "u-88231", "exp": 1789012345 }
A practical compromise is short-lived JWTs plus revocation of the refresh token, accepting a bounded window during which a revoked session still works. Where instant revocation is a hard requirement — payments, administrative access — an API gateway can introspect centrally and cache the result for a few seconds.
Security rules that are not optional
- Register exact redirect URIs and match them by exact string comparison. Wildcards and prefix matching are how tokens get redirected to attacker-controlled paths. Open redirects anywhere on the registered host reintroduce the same problem.
- Always send PKCE, always check
state. They defend different attacks: PKCE binds the code to the client,statebinds the response to the session. - Never put tokens in query strings. URLs end up in access logs, proxies and referrer headers.
- Bind tokens to the sender where the risk justifies it. Mutual-TLS certificate binding (RFC 8705) or DPoP (RFC 9449) makes a stolen token useless without the corresponding key.
- Validate the
issparameter on the authorization response when the client talks to more than one authorization server, to prevent mix-up attacks. - Do not use an access token to identify the user. Use OpenID Connect and its ID token, which is issued to your client and validated by it.
On the implementation side, most frameworks now do the right thing by default: Spring Security sends PKCE for both public and confidential clients and validates state for you. Write the flow yourself only if you must, and then follow the specification literally.
Key takeaways
- OAuth 2.0 delegates access to an API without sharing credentials; it deliberately says nothing about how the user authenticated.
- Values that travel through the browser are public; only the back channel may carry secrets, which is why the code flow exists.
- Use the authorization code flow with PKCE for every interactive client, client credentials for machine-to-machine calls and the device grant for input-constrained devices.
- Implicit and password grants are removed by RFC 9700; refresh tokens for public clients must rotate and be revoked as a chain on reuse.
- Scopes limit what a client may attempt — the API still has to authorize the user against the specific resource.
- Exact redirect-URI matching,
state, short access-token lifetimes and audience restriction turn a working integration into a safe one.
Sources and further reading
Frequently asked questions
- Is OAuth 2.0 a login protocol?
- No. It is a delegated authorization framework: it produces an access token that says a client may call an API with certain scopes, and it says nothing standard about who the user is or when they authenticated. Using an access token as proof of login is a well-known anti-pattern because the token was minted for an API, not for your application. OpenID Connect adds the identity layer that answers those questions.
- Do confidential clients still need PKCE?
- Yes. RFC 9700 requires PKCE for every authorization code exchange, not only for public clients. A client secret proves which application is redeeming the code, but PKCE additionally binds the code to the specific browser session that started the flow, which is what defeats code injection and code-interception attacks in shared redirect environments.
- Where should a single-page application keep its tokens?
- Preferably nowhere. The recommended pattern is a backend-for-frontend that performs the code exchange server-side and keeps tokens on the server, giving the browser only an HttpOnly session cookie. If the SPA must hold a token, keep it in memory rather than localStorage, use short lifetimes with refresh token rotation, and accept that any script injection on the page can exfiltrate it.
- What replaced the implicit and password grants?
- Both are removed by current best practice. Browser applications use the authorization code flow with PKCE, which never puts a token in a URL fragment and never exposes it to browser history or referrers. First-party applications that used the resource owner password credentials grant should redirect to the authorization server instead, so that multi-factor authentication, step-up and consent stay in one place.