| |

Node.js 53 🟢 OAuth2, OpenID Connect, and Social Login Integrations

⏱️ Estimated read: 17 min | |

Social login is the feature that lets users click “Sign in with Google” and arrive at your application without a password. Underneath, two protocols do the work. OAuth2 is the authorization framework that grants your application limited access to a user’s resources on another service. OpenID Connect is a thin identity layer on top of OAuth2 that adds authentication: it tells your application who the user is, not just what they can access . The distinction matters because OAuth2 alone cannot authenticate a user; it only authorizes access. OpenID Connect adds the identity claims that make social login possible. This chapter covers both protocols, the authorization code flow with PKCE that implements them, and the patterns for integrating Google, GitHub, and other providers into a Node.js application.

Key point: OAuth2 is about authorization, not authentication. OpenID Connect extends OAuth2 with identity. Use the authorization code flow with PKCE for every web application, and never use the implicit flow or the resource owner password credentials grant.


Why OpenID Connect exists

The authorization problem. OAuth2 lets a user grant an application access to their data on another service without sharing their password. The application receives an access token that represents the grant. The token says what the application can do, not who the user is. A social login feature needs the second piece of information.

The identity problem. Before OpenID Connect, applications built social login on top of OAuth2 by calling the provider’s user info endpoint and treating the result as identity. This worked but was fragile: the format varied by provider, the semantics were undefined, and there was no standard way to verify that the token was issued for this application.

The claims problem. OpenID Connect defines an ID token, a JSON Web Token that carries claims about the user: the subject identifier, the issuer, the audience (the client ID), the expiration, and optionally the user’s name, email, and profile picture. The token is signed by the provider, so the application can verify that it came from the expected issuer and was intended for this client .

The interoperability problem. OpenID Connect standardizes the endpoints and the token format. A client configured for one provider works with another by changing the endpoint URLs and the client credentials. The Passport passport-openidconnect strategy implements this standard and is the common integration point for Node.js applications .

The security problem. The implicit flow, which returns tokens directly in the URL fragment, is deprecated. The authorization code flow with PKCE is the current recommendation for all client types, including server-side applications and single-page applications .

The refresh token problem. Refresh tokens let an application obtain new access tokens without the user re-authenticating. For public clients, refresh tokens must be sender-constrained or use rotation. Rotation issues a new refresh token with each use and invalidates the old one; reuse of an old token signals theft and revokes the entire token family .


a. The authorization code flow with PKCE

The authorization code flow is a sequence of redirects and back-channel requests. The user is redirected to the provider, authenticates, and is redirected back to the application with an authorization code. The application exchanges the code for tokens over a back channel, so the tokens never appear in the browser’s address bar .

The PKCE extension

PKCE (Proof Key for Code Exchange) protects the authorization code from interception. The client generates a random string called the code verifier, hashes it with SHA-256, and base64-encodes the result to produce the code challenge. The challenge is sent with the authorization request. The verifier is sent with the token exchange. The provider hashes the verifier and checks that it matches the challenge. An attacker who intercepts the authorization code cannot exchange it without the verifier .

const crypto = require("crypto");

function generatePKCE() {
  const codeVerifier = crypto.randomBytes(32).toString("base64url");
  const codeChallenge = crypto
    .createHash("sha256")
    .update(codeVerifier)
    .digest("base64url");
  return { codeVerifier, codeChallenge };
}

The verifier is stored in the session between the authorization request and the callback. It is never sent to the browser.

The state parameter

The state parameter is an opaque value that the client sends with the authorization request and expects to receive back with the callback. It prevents CSRF attacks on the callback endpoint. The state must be generated with a cryptographically secure random number generator, stored in the session, and verified on return.

const state = crypto.randomBytes(16).toString("hex");
req.session.oauthState = state;
req.session.pkceVerifier = codeVerifier;

The state and verifier are bound to the user’s session. A callback that does not match the stored state is rejected.

The flow sequence

The complete flow is: the application redirects the user to the authorization endpoint with the client ID, redirect URI, scope, state, and code challenge. The provider authenticates the user and redirects back with the authorization code and the state. The application verifies the state, then makes a back-channel request to the token endpoint with the code, the client credentials, the redirect URI, and the code verifier. The provider returns the ID token, access token, and refresh token. The application validates the ID token and creates a session .


b. Integrating with Passport

Passport is the standard authentication middleware for Express. The passport-openidconnect strategy implements the OpenID Connect protocol and handles the redirects, token exchange, and profile extraction .

Strategy configuration

The strategy needs the provider’s issuer, authorization URL, token URL, user info URL, the client ID and secret, and the callback URL. These values come from the provider’s developer console.

const passport = require("passport");
const OpenIDConnectStrategy = require("passport-openidconnect");

passport.use(new OpenIDConnectStrategy({
  issuer: "https://accounts.google.com",
  authorizationURL: "https://accounts.google.com/o/oauth2/v2/auth",
  tokenURL: "https://oauth2.googleapis.com/token",
  userInfoURL: "https://openidconnect.googleapis.com/v1/userinfo",
  clientID: process.env.GOOGLE_CLIENT_ID,
  clientSecret: process.env.GOOGLE_CLIENT_SECRET,
  callbackURL: "/auth/google/callback",
  scope: ["openid", "profile", "email"],
}, function verify(issuer, profile, cb) {
  // Find or create the user in your database.
  User.findOrCreate({
    where: { provider: issuer, providerId: profile.id },
    defaults: { displayName: profile.displayName, email: profile.email },
  }).then(([user]) => cb(null, user)).catch(cb);
}));

The verify function receives the issuer and the profile. It is responsible for finding or creating the user record and calling the callback with the user object.

The routes

Two routes are needed: one to initiate the flow and one to handle the callback.

app.get("/auth/google",
  passport.authenticate("openidconnect"));

app.get("/auth/google/callback",
  passport.authenticate("openidconnect", {
    successRedirect: "/profile",
    failureRedirect: "/login",
  }));

The first route redirects the user to Google. The second handles the callback after Google redirects back. Passport handles the token exchange and calls the verify function .

Session serialization

Passport needs to serialize the user into the session and deserialize it on subsequent requests.

passport.serializeUser((user, done) => done(null, user.id));
passport.deserializeUser((id, done) => {
  User.findByPk(id).then((user) => done(null, user)).catch(done);
});

The serialized value is stored in the session. On each request, Passport deserializes it and attaches the user object to req.user.

Account linking

When a user signs in with a provider for the first time, the verify function creates a new user record. On subsequent sign-ins, it finds the existing record. The link between the provider account and the local user is stored in a table with columns for the provider (issuer) and the provider’s subject identifier (profile.id). This is the federated_credentials pattern .

db.get(
  "SELECT * FROM federated_credentials WHERE provider = ? AND subject = ?",
  [issuer, profile.id],
  (err, cred) => {
    if (cred) {
      // Existing link: find the user.
      db.get("SELECT * FROM users WHERE id = ?", [cred.user_id], cb);
    } else {
      // New link: create the user and the credential.
      db.run("INSERT INTO users (name) VALUES (?)", [profile.displayName], function () {
        db.run("INSERT INTO federated_credentials (user_id, provider, subject) VALUES (?, ?, ?)",
          [this.lastID, issuer, profile.id]);
        cb(null, { id: this.lastID, name: profile.displayName });
      });
    }
  }
);

The issuer and subject together form a globally unique identifier for the account at the provider. Two providers can have the same subject value without conflict because the issuer distinguishes them.


c. Provider-specific configuration

Each provider has its own developer console, its own client registration process, and its own endpoint URLs. The strategy configuration is the same in structure; only the values differ.

Google

Google’s OpenID Connect endpoints are well-known. The issuer is https://accounts.google.com, and the discovery document at https://accounts.google.com/.well-known/openid-configuration lists all endpoints.

passport.use(new OpenIDConnectStrategy({
  issuer: "https://accounts.google.com",
  authorizationURL: "https://accounts.google.com/o/oauth2/v2/auth",
  tokenURL: "https://oauth2.googleapis.com/token",
  userInfoURL: "https://openidconnect.googleapis.com/v1/userinfo",
  clientID: process.env.GOOGLE_CLIENT_ID,
  clientSecret: process.env.GOOGLE_CLIENT_SECRET,
  callbackURL: "/auth/google/callback",
  scope: ["openid", "profile", "email"],
}, verify));

Google requires the openid scope for OpenID Connect. The profile and email scopes add the claims for the user’s name and email address.

GitHub

GitHub does not implement OpenID Connect. It implements OAuth2, and the identity is obtained by calling the user API endpoint. The passport-github2 strategy handles this.

const GitHubStrategy = require("passport-github2").Strategy;

passport.use(new GitHubStrategy({
  clientID: process.env.GITHUB_CLIENT_ID,
  clientSecret: process.env.GITHUB_CLIENT_SECRET,
  callbackURL: "/auth/github/callback",
}, function (accessToken, refreshToken, profile, cb) {
  User.findOrCreate({
    where: { provider: "github", providerId: profile.id },
    defaults: { displayName: profile.displayName, email: profile.emails?.[0]?.value },
  }).then(([user]) => cb(null, user)).catch(cb);
}));

The verify function for GitHub receives the profile from the GitHub API, which includes the username, display name, and email. The email may be null if the user has not made it public.

The callback URL

The callback URL must match exactly what is registered in the provider’s console. A mismatch causes a redirect URI error. In development, the callback is typically http://localhost:3000/auth/<provider>/callback. In production, it is the HTTPS URL of the deployed application.

The scope

The scope determines which claims are available in the profile. For OpenID Connect providers, openid is required. Adding profile and email requests the corresponding claims. Some providers require additional scopes for specific data, such as user:email for GitHub.


Complete Example Session

// ============================================
// PART 1: GOOGLE OPENID CONNECT STRATEGY
// ============================================

const passport = require("passport");
const OpenIDConnectStrategy = require("passport-openidconnect");

passport.use(new OpenIDConnectStrategy({
  issuer: "https://accounts.google.com",
  authorizationURL: "https://accounts.google.com/o/oauth2/v2/auth",
  tokenURL: "https://oauth2.googleapis.com/token",
  userInfoURL: "https://openidconnect.googleapis.com/v1/userinfo",
  clientID: process.env.GOOGLE_CLIENT_ID,
  clientSecret: process.env.GOOGLE_CLIENT_SECRET,
  callbackURL: "/auth/google/callback",
  scope: ["openid", "profile", "email"],
}, async function verify(issuer, profile, cb) {
  try {
    const [user] = await User.findOrCreate({
      where: { provider: issuer, providerId: profile.id },
      defaults: {
        displayName: profile.displayName,
        email: profile.email,
      },
    });
    return cb(null, user);
  } catch (err) {
    return cb(err);
  }
}));

// ============================================
// PART 2: GITHUB OAUTH STRATEGY
// ============================================

const GitHubStrategy = require("passport-github2").Strategy;

passport.use(new GitHubStrategy({
  clientID: process.env.GITHUB_CLIENT_ID,
  clientSecret: process.env.GITHUB_CLIENT_SECRET,
  callbackURL: "/auth/github/callback",
  scope: ["user:email"],
}, async function (accessToken, refreshToken, profile, cb) {
  try {
    const [user] = await User.findOrCreate({
      where: { provider: "github", providerId: profile.id },
      defaults: {
        displayName: profile.displayName || profile.username,
        email: profile.emails?.[0]?.value,
      },
    });
    return cb(null, user);
  } catch (err) {
    return cb(err);
  }
}));

// ============================================
// PART 3: SESSION SERIALIZATION
// ============================================

passport.serializeUser((user, done) => done(null, user.id));

passport.deserializeUser(async (id, done) => {
  try {
    const user = await User.findByPk(id);
    done(null, user);
  } catch (err) {
    done(err);
  }
});

// ============================================
// PART 4: EXPRESS ROUTES
// ============================================

const express = require("express");
const session = require("express-session");
const app = express();

app.use(session({
  secret: process.env.SESSION_SECRET,
  resave: false,
  saveUninitialized: false,
  cookie: { httpOnly: true, secure: true, sameSite: "lax" },
}));

app.use(passport.initialize());
app.use(passport.session());

// Initiate Google login
app.get("/auth/google",
  passport.authenticate("openidconnect"));

// Handle Google callback
app.get("/auth/google/callback",
  passport.authenticate("openidconnect", {
    successRedirect: "/profile",
    failureRedirect: "/login",
  }));

// Initiate GitHub login
app.get("/auth/github",
  passport.authenticate("github"));

// Handle GitHub callback
app.get("/auth/github/callback",
  passport.authenticate("github", {
    successRedirect: "/profile",
    failureRedirect: "/login",
  }));

// ============================================
// PART 5: PROTECTED ROUTE
// ============================================

function requireAuth(req, res, next) {
  if (!req.user) return res.redirect("/login");
  next();
}

app.get("/profile", requireAuth, (req, res) => {
  res.json({
    id: req.user.id,
    displayName: req.user.displayName,
    email: req.user.email,
  });
});

// ============================================
// PART 6: MANUAL PKCE IMPLEMENTATION
// ============================================

const crypto = require("crypto");

function generatePKCE() {
  const codeVerifier = crypto.randomBytes(32).toString("base64url");
  const codeChallenge = crypto
    .createHash("sha256")
    .update(codeVerifier)
    .digest("base64url");
  return { codeVerifier, codeChallenge };
}

// Start the flow
app.get("/auth/custom", (req, res) => {
  const { codeVerifier, codeChallenge } = generatePKCE();
  const state = crypto.randomBytes(16).toString("hex");

  req.session.pkceVerifier = codeVerifier;
  req.session.oauthState = state;

  const params = new URLSearchParams({
    response_type: "code",
    client_id: process.env.CUSTOM_CLIENT_ID,
    redirect_uri: "https://app.example.com/auth/custom/callback",
    scope: "openid profile email",
    state,
    code_challenge: codeChallenge,
    code_challenge_method: "S256",
  });

  res.redirect(`https://provider.example.com/authorize?${params}`);
});

// Handle the callback
app.get("/auth/custom/callback", async (req, res) => {
  const { code, state } = req.query;

  if (state !== req.session.oauthState) {
    return res.status(403).send("Invalid state");
  }

  const response = await fetch("https://provider.example.com/token", {
    method: "POST",
    headers: { "Content-Type": "application/x-www-form-urlencoded" },
    body: new URLSearchParams({
      grant_type: "authorization_code",
      code,
      redirect_uri: "https://app.example.com/auth/custom/callback",
      client_id: process.env.CUSTOM_CLIENT_ID,
      client_secret: process.env.CUSTOM_CLIENT_SECRET,
      code_verifier: req.session.pkceVerifier,
    }),
  });

  const tokens = await response.json();
  // Validate tokens.id_token, create session, redirect.
  res.redirect("/profile");
});

The six parts showed Google and GitHub strategies, session serialization, Express routes, a protected route, and a manual PKCE implementation for a custom provider. The same Express application ran through every part, showing how the strategies plug into Passport and how the manual flow works underneath.


Quick Reference

OAuth2 vs OpenID Connect

AspectOAuth2OpenID Connect
PurposeAuthorizationAuthentication + Authorization
TokenAccess tokenID token + access token
ClaimsScopesID token claims (sub, iss, aud)
User infoCustom endpointStandard UserInfo endpoint
Use caseAPI access on behalf of userLogin with a provider

Authorization Flows

FlowStatusUse Case
Authorization code + PKCERecommendedAll clients
ImplicitDeprecatedDo not use
Client credentialsMachine-to-machineServer-to-server
Resource owner passwordProhibitedDo not use

Common Providers

ProviderProtocolStrategy
GoogleOpenID Connectpassport-openidconnect
GitHubOAuth2passport-github2
FacebookOAuth2passport-facebook
MicrosoftOpenID Connectpassport-azure-ad
Auth0OpenID Connectpassport-openidconnect

Key Parameters

ParameterPurpose
client_idIdentifies the application
redirect_uriWhere the provider redirects after auth
scopeWhat claims/access are requested
stateCSRF protection for the callback
code_challengePKCE challenge
code_verifierPKCE verifier (token exchange)

Best Practices

✅ Do This:

// Use the authorization code flow with PKCE.
const { codeVerifier, codeChallenge } = generatePKCE();  // ✅

// Generate a random state and verify it on callback.
req.session.oauthState = crypto.randomBytes(16).toString("hex");  // ✅

// Store the user's provider ID and issuer together.
{ provider: issuer, providerId: profile.id }  // ✅

// Use HTTPS for the callback URL in production.
callbackURL: "https://app.example.com/auth/google/callback"  // ✅

// Request only the scopes you need.
scope: ["openid", "profile", "email"]  // ✅

// Rotate refresh tokens and detect reuse.
// Issue a new refresh token with each refresh.  // ✅

❌ Don’t Do This:

// Don't use the implicit flow.
response_type: "token"  // ❌ Deprecated, tokens in URL

// Don't skip the state parameter.
// No state → CSRF on callback.  // ❌

// Don't store tokens in localStorage.
localStorage.setItem("access_token", token)  // ❌ XSS can steal it

// Don't trust the profile without validating the ID token.
// Verify iss, aud, exp, and signature.  // ❌

// Don't use the resource owner password grant.
grant_type: "password"  // ❌ Prohibited by OAuth 2.1

// Don't hardcode client secrets.
clientSecret: "my-secret"  // ❌ Use environment variables

Common Pitfalls

PitfallWhy It HappensFix
redirect_uri_mismatchCallback URL differs from consoleMatch exactly
State validation failsState not stored in sessionStore before redirect
PKCE failsVerifier not sent with token exchangeInclude code_verifier
ID token invalidWrong issuer or audienceVerify iss and aud claims
Email is null (GitHub)User has not made email publicRequest user:email scope
Session not persistedPassport serialize/deserialize missingImplement both
Token expiredNo refresh logicImplement refresh token rotation
CSRF on callbackNo state parameterGenerate and verify state

Real-World Examples

1. Google Strategy

new OpenIDConnectStrategy({
  issuer: "https://accounts.google.com",
  clientID: process.env.GOOGLE_CLIENT_ID,
  clientSecret: process.env.GOOGLE_CLIENT_SECRET,
  callbackURL: "/auth/google/callback",
  scope: ["openid", "profile", "email"],
}, verify)

2. GitHub Strategy

new GitHubStrategy({
  clientID: process.env.GITHUB_CLIENT_ID,
  clientSecret: process.env.GITHUB_CLIENT_SECRET,
  callbackURL: "/auth/github/callback",
}, verify)

3. PKCE Generation

const codeVerifier = crypto.randomBytes(32).toString("base64url")
const codeChallenge = crypto.createHash("sha256").update(codeVerifier).digest("base64url")

4. State Verification

if (req.query.state !== req.session.oauthState) return res.status(403)

5. Session Serialization

passport.serializeUser((user, done) => done(null, user.id))

6. Find or Create User

User.findOrCreate({ where: { provider: issuer, providerId: profile.id } })

7. Protected Route

app.get("/profile", requireAuth, (req, res) => res.json(req.user))

8. Token Exchange

fetch("https://provider/token", { method: "POST", body: new URLSearchParams({ code, code_verifier }) })

9. Refresh Token Rotation

// Issue new refresh token with each refresh; invalidate old.

10. Logout

app.get("/logout", (req, res) => {
  req.logout(() => res.redirect("/"));
})

Visual

The Authorization Code Flow with PKCE

┌────────────────────────────────────────────────────────────┐
│  AUTHORIZATION CODE FLOW WITH PKCE                         │
│                                                            │
│  CLIENT                    PROVIDER                        │
│  ──────                    ────────                        │
│                                                            │
│  1. Generate code_verifier (random)                        │
│     code_challenge = SHA256(verifier)                      │
│     state = random                                         │
│                                                            │
│  2. Redirect ──────────────────────▶ /authorize            │
│     client_id, redirect_uri, scope,                        │
│     state, code_challenge                                  │
│                                                            │
│                            3. User authenticates           │
│                                                            │
│  4. ◀────────────────────────────── Redirect to callback   │
│     code, state                                            │
│                                                            │
│  5. Verify state matches.                                  │
│                                                            │
│  6. POST /token ──────────────────▶ grant_type=code        │
│     code, redirect_uri, client_id,                         │
│     client_secret, code_verifier                           │
│                                                            │
│  7. ◀────────────────────────────── { id_token,            │
│                                       access_token,        │
│                                       refresh_token }      │
│                                                            │
│  8. Validate id_token (iss, aud, exp).                     │
│     Create session.                                        │
│                                                            │
│  The tokens never appear in the browser's address bar.     │
│  PKCE prevents code interception.                          │
│  State prevents CSRF on the callback.                      │
│                                                            │
└────────────────────────────────────────────────────────────┘

OAuth2 vs OpenID Connect

┌────────────────────────────────────────────────────────────┐
│  OAUTH2 AND OPENID CONNECT LAYERS                          │
│                                                            │
│  ┌──────────────────────────────────────────────────┐     │
│  │  OPENID CONNECT                                   │     │
│  │    Identity layer                                 │     │
│  │    ID token with claims                           │     │
│  │    UserInfo endpoint                              │     │
│  │    Answers: "Who is this user?"                   │     │
│  └──────────────────────────────────────────────────┘     │
│                        │                                   │
│                        v                                   │
│  ┌──────────────────────────────────────────────────┐     │
│  │  OAUTH 2.0                                        │     │
│  │    Authorization framework                        │     │
│  │    Access tokens, scopes, grants                  │     │
│  │    Answers: "What can this app access?"           │     │
│  └──────────────────────────────────────────────────┘     │
│                                                            │
│  OpenID Connect is built on top of OAuth 2.0.              │
│  The ID token is the authentication artifact.              │
│  The access token is the authorization artifact.           │
└────────────────────────────────────────────────────────────┘

The PKCE Protection

┌────────────────────────────────────────────────────────────┐
│  PKCE: PREVENTING CODE INTERCEPTION                        │
│                                                            │
│  WITHOUT PKCE                                              │
│  1. Attacker intercepts authorization code.                │
│  2. Attacker exchanges code for tokens.                    │
│  3. Attacker has access.                                   │
│                                                            │
│  WITH PKCE                                                 │
│  1. Client sends code_challenge with auth request.         │
│  2. Attacker intercepts code.                              │
│  3. Attacker cannot exchange code without code_verifier.   │
│  4. The verifier is never sent to the browser.             │
│                                                            │
│  The provider hashes the verifier and checks the match.    │
│  A code without a verifier is useless.                     │
└────────────────────────────────────────────────────────────┘

Account Linking

┌────────────────────────────────────────────────────────────┐
│  ACCOUNT LINKING                                           │
│                                                            │
│  users table                                               │
│  ┌──────────────────────────────────────────────────┐     │
│  │  id | display_name | email                        │     │
│  │  1  | Alice        | alice@example.com            │     │
│  └──────────────────────────────────────────────────┘     │
│                        │                                   │
│                        │  1:N                              │
│                        v                                   │
│  federated_credentials table                               │
│  ┌──────────────────────────────────────────────────┐     │
│  │  user_id | provider              | subject        │     │
│  │  1       | https://accounts.google│ 123456789     │     │
│  │  1       | github.com            | 987654321     │     │
│  └──────────────────────────────────────────────────┘     │
│                                                            │
│  The issuer + subject pair is unique per provider account. │
│  A user can link multiple provider accounts.               │
│  On login, look up by (provider, subject).                 │
└────────────────────────────────────────────────────────────┘

Summary

ItemValue
OAuth2Authorization framework
OpenID ConnectIdentity layer on top of OAuth2
ID tokenJWT with user identity claims
Authorization code flowThe recommended grant
PKCEProof Key for Code Exchange
StateCSRF protection for the callback
passport-openidconnectPassport strategy for OIDC
passport-github2Passport strategy for GitHub
verify functionFinds or creates the user
Account linking(issuer, subject) identifies the provider account

Key takeaways:

  • OAuth2 authorizes, OpenID Connect authenticates. OAuth2 grants access to resources. OpenID Connect adds identity. Social login needs both.
  • Use the authorization code flow with PKCE. The implicit flow is deprecated, and the resource owner password grant is prohibited. Authorization code with PKCE is the recommendation for all clients .
  • PKCE prevents code interception. The code verifier is never sent to the browser, so an intercepted authorization code cannot be exchanged. The provider verifies the challenge against the verifier .
  • The state parameter prevents CSRF. Generate a random state, store it in the session, and verify it on the callback. A missing or mismatched state means the callback is not trusted.
  • The verify function is where account linking happens. It receives the issuer and profile, looks up the (provider, providerId) pair, and creates the user if none exists .
  • Store the issuer and subject together. Two providers can issue the same subject identifier. The issuer disambiguates. The pair is the unique key for a federated account.
  • Rotate refresh tokens and detect reuse. For public clients, a new refresh token is issued with each refresh. Reuse of an old token signals theft and revokes the token family .
  • Validate the ID token. Check the issuer, audience, expiration, and signature. Never trust a profile without verifying that the token was issued by the expected provider and intended for your client.

Remember: Social login is built on two protocols that are easy to confuse. OAuth2 is the authorization framework; OpenID Connect is the identity layer on top. The authorization code flow with PKCE is the current standard, and the implicit flow is deprecated. The state parameter prevents CSRF, and PKCE prevents code interception. Passport’s passport-openidconnect strategy implements the standard and handles the redirects, token exchange, and profile extraction. The verify function is where the application finds or creates the user, linking the provider account to a local record through the (issuer, subject) pair. Refresh tokens must be rotated, and the ID token must be validated. Every one of these details is necessary, and omitting any of them creates a specific, known weakness.


Was this helpful?


Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!