With Passport in an Express app, how does passport-openidconnect turn a provider callback into a user, and why does passport-google-oauth20 never read the id_token?
answer
- same contract, different credential
- two routes, one strategy name
- profile parsed from ID token claims
- issuer plus subject identifies the account
- Google strategy calls userinfo instead
basics
~20 spassport-openidconnect exchanges the code, checks the ID token's issuer, audience and expiry, builds the profile from its claims and calls verify(issuer, profile, cb). passport-google-oauth20, an OAuth 2.0 strategy, fetches the profile from userinfo with the access token.
solid answer
~50 sBoth strategies keep Passport's contract: they collect a credential and hand a profile to your verify callback, which calls `cb` with a user. With `passport-openidconnect`, both the login route and the callback route call `passport.authenticate('openidconnect')`. The first redirects to the provider; on the callback the strategy exchanges the code at `tokenURL`, requires an `id_token`, checks `iss` against `issuer`, `aud` and `azp` against `clientID`, and `exp`, and by default builds the profile from the ID token's claims without calling userinfo. Your `verify(issuer, profile, cb)` links the account by issuer and `profile.id`, the subject. `passport-google-oauth20` extends the generic OAuth 2.0 strategy: its verify gets `(accessToken, refreshToken, profile, cb)` and the profile comes from a userinfo request made with the access token. Its code never reads the `id_token`, so identity rests on that userinfo call rather than on ID-token claims.
code
javascript · 22 linesconst passport = require('passport');
const OpenIDConnectStrategy = require('passport-openidconnect');
const { findOrLinkFederatedUser } = require('./users');
passport.use(new OpenIDConnectStrategy({
issuer: process.env.OIDC_ISSUER,
authorizationURL: process.env.OIDC_AUTHORIZATION_URL,
tokenURL: process.env.OIDC_TOKEN_URL,
clientID: process.env.OIDC_CLIENT_ID,
clientSecret: process.env.OIDC_CLIENT_SECRET,
callbackURL: process.env.OIDC_CALLBACK_URL,
scope: ['profile', 'email']
}, (issuer, profile, cb) => {
findOrLinkFederatedUser(issuer, profile.id, profile.displayName)
.then((user) => cb(null, user || false), cb);
}));
app.get('/oidc/login', passport.authenticate('openidconnect'));
app.get('/oidc/callback',
passport.authenticate('openidconnect', { failureRedirect: '/login', failureMessage: true }),
(req, res) => res.redirect('/')
);go deeper
Recall that an OpenID Connect login is still a Passport strategy with a verify callback, used on two routes: one that redirects and one that handles the callback.
Explain what the OIDC strategy passes to verify, that the profile comes from the ID token by default, and why accounts link on issuer and subject.
Contrast where identity comes from in each strategy, the 403 failures from claim checks, and how verify.length decides the arguments and can silently break a callback.
Decide which provider integrations the team standardises on a generic OIDC strategy versus provider-specific packages, weighing claim checks, round trips and upkeep.
## The scenario An app lets people sign in with a username and password and also through an OpenID Connect provider. In Passport both are just strategies: `passport-local` registered as `'local'`, and `passport-openidconnect` registered as `'openidconnect'`. The verify callback contract is identical; only the credential differs. For the local strategy it is a password; for an OIDC strategy it is the provider's statement about who signed in. ## How `passport-openidconnect` runs You construct it with the provider's endpoints and your client registration: `issuer`, `authorizationURL`, `tokenURL`, optionally `userInfoURL`, `clientID`, `clientSecret` and `callbackURL`. The constructor throws if `issuer`, `authorizationURL`, `tokenURL`, `clientID` or the verify function is missing. Two routes then use the same strategy name: 1. `GET /login` runs `passport.authenticate('openidconnect')`. With no `code` in the query, the strategy builds an authorization request (`response_type=code`, scope `openid` plus any `scope` you add), stores a state handle in the session, and redirects. 2. `GET /cb` runs it again. Now `req.query.code` is present, so the strategy checks the stored state, exchanges the code at `tokenURL`, and requires an `id_token` in the token response. 3. It decodes the ID token's payload and checks the claims it needs: `iss` must equal the configured `issuer`, `aud` (and `azp`, when present) must match `clientID`, `exp` must be in the future, and `nonce` and `max_age` are checked when you configured them. A mismatch is a **failure with status 403**, not an error. 4. It builds a normalized **profile** from the claims: `profile.id` from `sub`, `displayName` from `name`, `emails` from `email`. 5. It calls your verify callback. The state, nonce and code-verifier bookkeeping behind steps 1 to 3 belongs to the relying-party material in the authentication tree, and validating a JWT in general is covered with JWT validation. What is specific here is the order: the strategy decodes the token it received directly from the token endpoint and checks those claims; its own code does not verify a signature. ## The verify callback and its arity `passport-openidconnect` picks the arguments it passes by the **declared parameter count** of your verify function (`verify.length`): | Parameters | Arguments received | |---|---| | 3 | `issuer, profile, cb` | | 4 | `issuer, profile, context, cb` | | 5 | `issuer, profile, context, idToken, cb` | | 7 | `issuer, profile, context, idToken, accessToken, refreshToken, cb` | | 8 | the 7 form with `params` before `cb` | | 9 | `issuer, uiProfile, idProfile, context, idToken, accessToken, refreshToken, params, cb` | Two consequences matter. First, since version 0.1.0 the profile comes from the ID token and **userinfo is not fetched** unless your verify takes the 9-parameter form or you set `skipUserProfile: false`; whether `name` or `email` is present then depends on which claims the provider puts in the ID token for your scopes. Second, a default value or rest parameter changes `verify.length`, so the strategy may pass a different argument list than the one you declared; and without `passReqToCallback`, a count it does not list, such as six, falls back to the three-argument call. Inside the callback the job is account linking: - Look up a federated credential by the pair **issuer + `profile.id`**; the subject is only unique per issuer. - On the first sign-in, create the user and the link; afterwards, load the linked user. - Call `cb(null, user)`, `cb(null, false)` or `cb(err)` exactly as with the local strategy. ## Why the Google strategy ignores the `id_token` `passport-google-oauth20` is built on the generic OAuth 2.0 strategy and names itself `'google'`. Its verify callback is `(accessToken, refreshToken, profile, cb)`. After the code exchange it overrides `userProfile()` to call a userinfo endpoint (`userProfileURL`, which defaults to Google's v3 userinfo URL) with the **access token**, and parses that JSON into the profile. Nothing in the strategy reads the `id_token` from the token response. That is a design choice of an OAuth 2.0 strategy, not an oversight to patch around: - Identity comes from an authenticated API call, so the trust rests on the access token and the userinfo response, not on ID-token claims. - Every sign-in costs one more round trip. - There is no nonce or audience check on an ID token, because none is used. If you want sign-in driven by ID-token claims from that provider, configure `passport-openidconnect` with its issuer and endpoints instead. ## What to say in an interview - Same Passport contract, so the login route, `failureRedirect` and the error path behave like the local strategy. - The OIDC strategy reads identity from the ID token by default; the Google OAuth 2.0 strategy reads it from userinfo. - Link accounts on issuer and subject rather than on email alone.
- What does passport-openidconnect do when the provider redirects back with error=access_denied?It treats it as a failed login: `this.fail({ message: error_description })`, so `failureRedirect` or the default 401 applies and `failureMessage` can show the text. Any other `error` value becomes an `AuthorizationError` passed to `this.error`, which reaches your error middleware through `next(err)`.
- Your OIDC verify function is declared as (issuer, profile, context, idToken, accessToken, cb). What goes wrong?That is six parameters, and without `passReqToCallback` the strategy has no six-parameter form, so it falls back to calling `verify(issuer, profile, verified)`. `context` receives Passport's done function and `cb` is undefined, so calling `cb` throws a TypeError instead of completing the login. Use a listed count, such as seven with `refreshToken` added.
- passport-google-oauth20 validates the id_token before calling verify
- OIDC sign-in needs a different callback contract than local login
- passport-openidconnect always fetches userinfo on every sign-in
- Linking federated accounts by email address alone is safe
- An issuer mismatch in the ID token is reported as a 500 error