Apply Now Apply Now Apply Now
header_logo
Post thumbnail
FULL STACK DEVELOPMENT

OAuth 2.0 Explained: How Web Applications Handle User Authentication

By Vishalini Devarajan

You have probably clicked “Continue with Google” a hundred times. Behind that single click, the app never sees your Google password, yet it still gets your name and email. That is OAuth 2.0 at work.

Web applications constantly need to act on a user’s behalf: read their calendar, post to their account, or verify who they are. Asking users to hand over passwords is unsafe. OAuth 2.0 solves this with scoped, revocable tokens. This OAuth 2.0 tutorial walks you through the concepts, the flow, the grant types, and a working Node.js implementation, plus the security practices that keep it safe.

Table of contents


  1. What Is OAuth 2.0?
    • Authentication vs Authorization
    • Ready to Build Secure, Real-World Applications?
    • Where Is It Used?
  2. Key Components of OAuth 2.0
  3. How Does OAuth 2.0 Work?
  4. Different Types of OAuth 2.0 Grant Types
  5. OAuth 2.0 Implementation in Node.js
    • Step 1: Set Up the Project
    • Step 2: Configure the Provider
    • Step 3: Redirect Users to the Authorization Server
    • Step 4: Handle the Callback and Exchange the Code
    • Step 5: Access Protected Resources
    • Step 6: Refresh the Access Token
    • Security Considerations for Your Implementation
  6. OAuth vs JWT: What Is the Difference?
  7. Common OAuth 2.0 Security Risks and Best Practices
  8. Real-World Applications of OAuth 2.0
  9. Conclusion
  10. Frequently Asked Questions
    • What is OAuth 2.0, and why is it used?
    • Is OAuth 2.0 an authentication or authorization protocol?
    • What is the difference between OAuth and JWT?
    • How does OAuth 2.0 work in Node.js?
    • Is OAuth 2.0 secure for web applications?

What Is OAuth 2.0?

OAuth 2.0 is an authorization framework that lets an application access a user’s resources on another service without ever receiving the user’s password. Instead, the app receives an access token with limited permissions (called scopes) and a limited lifetime.

Authentication vs Authorization

  • Authentication answers: who are you?
  • Authorization answers: what are you allowed to do?

OAuth 2.0 handles authorization. When people talk about OAuth 2.0 authentication, such as social login, they usually mean OpenID Connect (OIDC), a thin identity layer built on top of OAuth 2.0 that adds an ID token describing the user.

Ready to Build Secure, Real-World Applications?

Authentication and API security are core skills for every backend and full-stack developer. Learn them hands-on with HCL GUVI’s Full Stack Development Course with Placement Assistance, covering Node.js, Express, databases, authentication, and deployment through project-based, mentor-led learning in your preferred language.

Where Is It Used?

Social login, “connect your GitHub account” integrations, apps reading Google Drive files, and enterprise single sign-on all rely on OAuth 2.0.

Key Components of OAuth 2.0

ComponentRoleExample
Resource OwnerThe user who owns the data and grants accessYou
Client ApplicationThe app requesting accessA task manager app
Authorization ServerAuthenticates the user and issues tokensGoogle Accounts
Resource ServerThe API that holds protected dataGoogle Calendar API
Access TokenShort-lived credential used to call the APIA token valid for ~1 hour
Refresh TokenLong-lived credential used to get new access tokensStored securely on the server
Authorization CodeTemporary code exchanged for tokens after user consentA one-time string in the redirect URL

How Does OAuth 2.0 Work?

Let’s follow the OAuth 2.0 flow using a familiar scenario: a user signs into a web app with Google.

  1. User clicks “Sign in with Google.” The app redirects the browser to Google’s authorization endpoint with its client ID, requested scopes, redirect URI, a state value, and a PKCE code challenge.
  2. User logs in and consents. This happens on Google’s page. The app never sees the password.
  3. Google redirects back to the app’s redirect URI with a one-time authorization code and the same state.
  4. The app verifies state, then sends the code (plus the PKCE verifier) directly to Google’s token endpoint from its backend.
  5. Google returns tokens: an access token, usually a refresh token if requested, and an ID token when OIDC scopes are used.
  6. The app calls the resource server with the access token in the Authorization: Bearer header.
  7. When the access token expires, the app uses the refresh token to get a new one without bothering the user.
User/Browser        Client App          Authorization Server     Resource Server

     |  click login      |                        |                     |

     |------------------>|                        |                     |

     |<--- redirect to /authorize ----------------|                     |

     |-------- login + consent ------------------>|                     |

     |<--- redirect back with ?code=...&state=... |                     |

     |------------------>|-- code + verifier ---->|                     |

     |                   |<-- access/refresh token|                     |

     |                   |------------- Bearer token ------------------>|

     |                   |<------------- protected data ----------------|

The key idea: the code travels through the browser, but the tokens travel over a direct back-channel between your server and the authorization server.

Also checkout: Building Secure Authentication by Setting Up JWT in a Node.js App

Different Types of OAuth 2.0 Grant Types

A grant type is the method a client uses to obtain tokens. Pick based on who the client is and whether a user is involved.

Grant TypePurposeBest For
Authorization Code + PKCEUser-delegated access with strong protection against code interceptionWeb apps, SPAs, mobile apps
Client CredentialsApp authenticates as itself, no user involvedMachine-to-machine, backend services
Device AuthorizationUser approves on a second deviceSmart TVs, CLI tools, IoT
Refresh TokenExchanges a refresh token for a new access tokenKeeping sessions alive silently

Authorization Code with PKCE is the recommended default for almost everything. PKCE (Proof Key for Code Exchange) binds the authorization request to the token request, so a stolen code is useless on its own.

Deprecated grants: The Resource Owner Password Credentials grant makes the app collect the user’s username and password directly. That defeats the entire purpose of OAuth, breaks multi-factor authentication, and is removed in OAuth 2.1, so do not use it in new projects. The Implicit grant, which returned tokens in the URL, is similarly discouraged in favor of Authorization Code with PKCE.

Also checkout: Protecting Routes with JWT Middleware in Node.js (2026 Guide)

OAuth 2.0 Implementation in Node.js

Let’s build a minimal Express app that signs users in with Google using Authorization Code + PKCE. We’ll use plain Node libraries so every step stays visible.

Step 1: Set Up the Project

bash

mkdir oauth-demo && cd oauth-demo

npm init -y

npm install express express-session axios dotenv

Set "type": "module" in package.json to use import syntax.

Step 2: Configure the Provider

Create OAuth credentials in the Google Cloud Console, add http://localhost:3000/callback as an authorized redirect URI, and store the values in .env:

CLIENT_ID=your-client-id

CLIENT_SECRET=your-client-secret

REDIRECT_URI=http://localhost:3000/callback

SESSION_SECRET=a-long-random-string

Step 3: Redirect Users to the Authorization Server

js

import express from "express";

import session from "express-session";

import crypto from "crypto";

import axios from "axios";

import "dotenv/config";

const app = express();

app.use(session({

  secret: process.env.SESSION_SECRET,

  resave: false,

  saveUninitialized: false,

  cookie: { httpOnly: true, sameSite: "lax" } // add secure: true in production

}));

const b64url = (buf) => buf.toString("base64url");

app.get("/login", (req, res) => {

  const state = b64url(crypto.randomBytes(16));

  const verifier = b64url(crypto.randomBytes(32));

  const challenge = b64url(crypto.createHash("sha256").update(verifier).digest());

  req.session.state = state;

  req.session.verifier = verifier;

  const params = new URLSearchParams({

    client_id: process.env.CLIENT_ID,

    redirect_uri: process.env.REDIRECT_URI,

    response_type: "code",

    scope: "openid email profile",

    state,

    code_challenge: challenge,

    code_challenge_method: "S256",

    access_type: "offline" // Google-specific: request a refresh token

  });

  res.redirect(`https://accounts.google.com/o/oauth2/v2/auth?${params}`);

});

What this does: It generates a random state (CSRF protection) and a PKCE verifier, saves both in the server-side session, and sends only the hashed challenge to the authorization server.

GUVI Ad

Step 4: Handle the Callback and Exchange the Code

js

app.get("/callback", async (req, res) => {

  const { code, state } = req.query;

  if (!state || state !== req.session.state) {

    return res.status(403).send("Invalid state");

  }

  try {

    const { data } = await axios.post(

      "https://oauth2.googleapis.com/token",

      new URLSearchParams({

        code,

        client_id: process.env.CLIENT_ID,

        client_secret: process.env.CLIENT_SECRET,

        redirect_uri: process.env.REDIRECT_URI,

        grant_type: "authorization_code",

        code_verifier: req.session.verifier

      })

    );

    req.session.tokens = data; // access_token, refresh_token, expires_in

    delete req.session.state;

    delete req.session.verifier;

    res.redirect("/profile");

  } catch (err) {

    res.status(500).send("Token exchange failed");

  }

});

What this does: It rejects the request if state doesn’t match, then exchanges the code plus the original verifier for tokens over a direct server-to-server call.

Step 5: Access Protected Resources

js

app.get("/profile", async (req, res) => {

  if (!req.session.tokens) return res.redirect("/login");

  const { data } = await axios.get(

    "https://www.googleapis.com/oauth2/v3/userinfo",

    { headers: { Authorization: `Bearer ${req.session.tokens.access_token}` } }

  );

  res.json(data);

});

app.listen(3000, () => console.log("Running on http://localhost:3000"));

Step 6: Refresh the Access Token

When the access token expires and you hold a refresh token, request a new one:

js

async function refreshAccessToken(refreshToken) {

  const { data } = await axios.post(

    "https://oauth2.googleapis.com/token",

    new URLSearchParams({

      client_id: process.env.CLIENT_ID,

      client_secret: process.env.CLIENT_SECRET,

      refresh_token: refreshToken,

      grant_type: "refresh_token"

    })

  );

  return data.access_token;

}

Security Considerations for Your Implementation

  • Validate state on every callback to block CSRF.
  • Use PKCE even for confidential clients.
  • Register exact redirect URIs with the provider and never accept arbitrary ones.
  • Store tokens server-side (encrypted session store or database), never in localStorage.
  • Keep secrets in environment variables, not in source code.

OAuth vs JWT: What Is the Difference?

This is one of the most common points of confusion. They are not competitors: OAuth 2.0 is a framework that defines how tokens are obtained, while JWT (JSON Web Token) is a token format.

AspectOAuth 2.0JWT
What it isAuthorization frameworkToken format (RFC 7519)
PurposeDelegate access to resourcesCarry signed claims securely
DefinesRoles, flows, grant types, endpointsHeader, payload, signature structure
RelationshipAccess tokens can be JWTs, or opaque stringsCan be used inside OAuth, or independently (e.g., sessions)
Typical use“Let this app read my calendar”“Here is a verifiable ID or access token”

In short, OAuth tells you how to get a token; JWT describes what a token can look like.

GUVI Ad

Also checkout: Why JSON Web Tokens Matter in Modern Authentication

Common OAuth 2.0 Security Risks and Best Practices

  • Token leakage: Never put tokens in URLs or logs. Send them in headers, and avoid exposing them to client-side JavaScript where possible.
  • Improper redirect URI validation: Use exact-match allowlists. Loose matching lets attackers steal authorization codes.
  • CSRF attacks: Always generate and verify a unique state per request.
  • Insecure token storage: Prefer server-side storage or HttpOnly, Secure cookies over browser storage.
  • Missing PKCE validation: Require PKCE so an intercepted code can’t be redeemed.
  • Long-lived access tokens: Keep them short (minutes to an hour) to limit damage if stolen.
  • Weak refresh token handling: Store refresh tokens encrypted, rotate them on use, and revoke them on logout or suspected compromise.
  • No HTTPS: Every OAuth endpoint and redirect URI must use HTTPS in production (plain HTTP on localhost is fine for development).

Real-World Applications of OAuth 2.0

  • Social login: Sign in with Google, GitHub, or Microsoft, so users skip creating yet another password.
  • Third-party integrations: A project tool posting updates to Slack on your behalf.
  • Cloud storage access: A document editor opening files from Google Drive or Dropbox with your consent.
  • External API connections: A dashboard pulling data from Spotify, Stripe, or Salesforce.
  • Enterprise authorization: Employees accessing internal apps through single sign-on, with services calling each other using the Client Credentials grant.

Conclusion

OAuth 2.0 lets applications access user data securely without ever touching passwords, using scoped, short-lived tokens that users can revoke at any time. Once you understand the roles, the Authorization Code flow with PKCE, and the security practices above, implementing it in Node.js becomes straightforward. Hopefully this OAuth 2.0 tutorial gives you a solid foundation to build on. Try the demo app, then experiment with different providers and scopes.

Frequently Asked Questions

1. What is OAuth 2.0, and why is it used?

OAuth 2.0 is an authorization framework that lets an application access a user’s resources on another service using tokens instead of passwords. It is used to enable secure third-party access, social login, and API integrations while giving users control over what is shared.

2. Is OAuth 2.0 an authentication or authorization protocol?

OAuth 2.0 is an authorization protocol. It grants access to resources but doesn’t verify identity on its own. For authentication, applications use OpenID Connect, which builds on OAuth 2.0 and adds an ID token.

3. What is the difference between OAuth and JWT?

OAuth 2.0 is a framework that defines how an app obtains access to resources. JWT is a compact, signed token format. OAuth access tokens are often issued as JWTs, but they can also be opaque strings, and JWTs can be used without OAuth.

4. How does OAuth 2.0 work in Node.js?

In Node.js, you redirect the user to the provider’s authorization endpoint with a state and PKCE challenge, handle the callback, verify state, exchange the authorization code for tokens on the server, and then call APIs with the access token. Libraries such as Passport.js or openid-client can simplify this.

5. Is OAuth 2.0 secure for web applications?

Yes, when implemented correctly. Use the Authorization Code flow with PKCE, validate state and redirect URIs, enforce HTTPS, keep access tokens short-lived, and store tokens securely. Most OAuth vulnerabilities come from implementation mistakes, not the protocol itself.

Success Stories

Did you enjoy this article?

Learn with HCL GUVI

Schedule 1:1 free counselling

Similar Articles

Loading...
Get in Touch
Chat on Whatsapp
Request Callback
Share logo Copy link
Table of contents Table of contents
Table of contents Articles
Close button

  1. What Is OAuth 2.0?
    • Authentication vs Authorization
    • Ready to Build Secure, Real-World Applications?
    • Where Is It Used?
  2. Key Components of OAuth 2.0
  3. How Does OAuth 2.0 Work?
  4. Different Types of OAuth 2.0 Grant Types
  5. OAuth 2.0 Implementation in Node.js
    • Step 1: Set Up the Project
    • Step 2: Configure the Provider
    • Step 3: Redirect Users to the Authorization Server
    • Step 4: Handle the Callback and Exchange the Code
    • Step 5: Access Protected Resources
    • Step 6: Refresh the Access Token
    • Security Considerations for Your Implementation
  6. OAuth vs JWT: What Is the Difference?
  7. Common OAuth 2.0 Security Risks and Best Practices
  8. Real-World Applications of OAuth 2.0
  9. Conclusion
  10. Frequently Asked Questions
    • What is OAuth 2.0, and why is it used?
    • Is OAuth 2.0 an authentication or authorization protocol?
    • What is the difference between OAuth and JWT?
    • How does OAuth 2.0 work in Node.js?
    • Is OAuth 2.0 secure for web applications?