How to Implement OAuth in Web Apps: Flows and Steps
To implement OAuth in a web app, register your application with an authorization server, send users there with the authorization code flow protected by PKCE, exchange the returned code for tokens on your server, and validate the access token on every API call. OAuth 2.0 is defined in RFC 6749, with bearer token use in RFC 6750.
- OAuth delegates authorization. Your app gets limited access without ever handling the user's password.
- Authorization code plus PKCE is the default. It suits server-side apps, single-page apps, and mobile clients.
- Four roles run every flow. Resource owner, client, authorization server, and resource server.
- Skip the legacy grants. Implicit and password flows are listed as legacy on oauth.net.
- Use a maintained library. Hand-rolled token handling is where implementations quietly go wrong.
What problem does OAuth solve?
OAuth lets an application act for a user at another service with the user's approval and within set limits. The application never sees or stores that user's password.
Before OAuth, integrations asked for credentials directly and received unlimited, unrevocable access. Tokens replaced that bargain with scoped, expiring, revocable permission.
The OAuth website describes OAuth 2.0 as the industry-standard protocol for authorization, developed in the IETF OAuth Working Group. Its specification is RFC 6749, published with companion documents.
Note what OAuth is not: it standardizes authorization, not login itself. OpenID Connect builds the identity layer on top of it when you need authenticated user profiles.
Keep the vocabulary straight in code reviews. Authentication asks who someone is; authorization asks what an application may do, and OAuth answers only the second question.
Who are the four roles in OAuth?
| Role | Who it is | Job in the flow |
|---|---|---|
| Resource owner | The user | Grants or denies access to their data |
| Client | Your web app | Requests access and calls the API |
| Authorization server | The identity provider | Authenticates the user and issues tokens |
| Resource server | The API | Checks tokens and serves protected data |
One system can play several roles. A provider may run both the authorization server and the API, but keeping the roles separate in your design prevents confused code.
Clients also split into two types. Confidential clients, like server-side web apps, can keep a secret; public clients, like browser apps, cannot, and that drives flow choice.
Classify your own client honestly before choosing anything else. A single-page app distributed to browsers is public even if your team wrote every line of it.
Which grant type should a web app use?
Use the authorization code grant, with PKCE, for anything acting on behalf of a user. The user's browser handles consent, while tokens move over a server-to-server channel.
PKCE, defined in RFC 7636, binds the code exchange to the client that started the flow. A stolen authorization code is useless without the original verifier.
Client credentials covers machine-to-machine calls where no user exists. The device code grant, RFC 8628, serves devices with no browser or keyboard, such as televisions.
The OAuth website lists the implicit flow and the password grant as legacy. New web apps should not implement either; both expose credentials or tokens in ways modern guidance rejects.
Whatever you connect, vet it like any other integration in your shadow IT inventory, because OAuth grants are standing access to company data.
How does the authorization code flow work?
- Your app generates a PKCE verifier and its hashed challenge
- The browser redirects to the authorization server with the challenge
- The user signs in and approves the requested scopes
- The server redirects back to your app with a short-lived code
- Your server exchanges the code and verifier at the token endpoint
- The server returns an access token, and usually a refresh token
- Your app calls the API with the token as a bearer credential
Two details carry the security of this flow. The state parameter ties the response to the request that started it, blocking cross-site request forgery.
The redirect URI must match the registered value exactly. Loose matching is how attackers steer codes to endpoints they control, so register precise URIs only.
Scopes keep the grant narrow. Request only the permissions the feature needs, because the consent screen and the token both inherit whatever you ask for.
Keep access tokens short-lived and let refresh tokens do the renewing. A token that lives for an hour limits the damage when one leaks into a log file.
Log the metadata of token events, never the tokens. Client ID, scopes granted, and timestamps debug most failures without creating a credential archive.
How do you implement OAuth step by step?
- Choose an authorization server or identity provider
- Register your app and record the client ID and secret
- Register exact redirect URIs for each environment
- Integrate a maintained OAuth library for your framework
- Build the authorize redirect with scopes, state, and PKCE
- Handle the callback: verify state, then exchange the code server-side
- Store tokens server-side and refresh them before expiry
- Validate tokens at your API on every request
Registration comes first because every later step references its outputs. Store the client secret in a secrets manager, never in source control or browser code.
Token validation follows RFC 6750's bearer model. Your API checks the token's signature or introspects it, then confirms expiry, issuer, audience, and scope before serving data.
Refresh tokens deserve the same care as passwords. Keep them server-side, rotate them where the provider supports it, and revoke them when a user disconnects the integration.
Test against the provider's sandbox or a local mock server first. Consent screens, error responses, and token formats differ enough between providers to punish assumptions.
For internal tools, route the same grants through your access reviews so standing third-party access gets re-approved on a cycle.
What are the common implementation mistakes?
Storing tokens in browser local storage is the classic error. Any script running on the page can read them, so server-side sessions or a backend-for-frontend pattern are safer.
Skipping state verification comes next. Without it, an attacker can inject a code obtained for their own account into a victim's session and link the wrong identity.
Accepting tokens without checking the audience is subtler. A token issued for another application must fail at your API, or any partner integration becomes your login.
Skipping PKCE on a public client completes the set. Without it, anyone who intercepts the authorization code from a redirect can exchange it for tokens.
Granting permanent offline access by default is quieter but similar. Refresh tokens should be issued when the use case needs them, not as a reflex.
Finally, test with a second client registration. Tokens and codes must never cross between clients, and only an explicit test proves your server enforces that.
- Wildcard or prefix-matched redirect URIs
- Client secrets shipped inside browser or mobile code
- Scopes requested far beyond the feature's needs
- Access tokens logged in URLs, analytics, or error reports
Test the unhappy paths before launch: expired codes, mismatched state, revoked refresh tokens, and a token minted for a different client. Each should fail closed.
How does OAuth 2.1 change things?
The next revision of the framework is an in-progress consolidation of the current specification and its common extensions, as the OAuth website describes it. It folds current security practice into one document.
The direction is consistent with the OAuth Security Best Current Practice, RFC 9700. PKCE becomes expected for authorization code flows, and the legacy grants fall away.
You do not need to wait for it. Implementing authorization code with PKCE, exact redirect matching, and short-lived tokens today puts you on the 2.1 path already.
Keep an eye on provider roadmaps rather than rewriting early. Your security team review cycle is the right place to track which extensions your providers adopt.
Document your flow choices while you build. The next engineer inherits your redirect URIs, scopes, and token storage, and undocumented OAuth setups rot quickly.
Review granted integrations periodically after launch. Users connect third-party clients over time, and yesterday's reasonable scope can become today's excess access.
Revoke decisively when a provider is breached or abandoned. Tokens you issued remain valid until they expire or you cut them off.
Sources
Frequently asked questions
What is OAuth in a web app?
It is the framework that lets your app access a user's data at another service with their approval, using scoped tokens instead of their password. OAuth 2.0 is defined in RFC 6749.
Which OAuth flow should a web app use?
The authorization code flow with PKCE. It keeps tokens off the browser channel, works for server-side and single-page apps, and matches current security guidance, including the direction of OAuth 2.1.
What is PKCE and why does it matter?
PKCE (RFC 7636) proves the client exchanging an authorization code is the one that started the flow. The client sends a hashed challenge first, then the original verifier at exchange, so intercepted codes cannot be redeemed.
Is OAuth the same as login?
No. OAuth standardizes authorization: what an app may access. OpenID Connect adds the identity layer on top of OAuth for sign-in and user profile claims.
Should I build my own OAuth implementation?
Use a maintained library or your provider's SDK. The protocol's security depends on details like state checks, exact redirect matching, and token validation that are easy to get subtly wrong by hand.