panva / openid-client

OAuth 2 / OpenID Connect Client API for JavaScript Runtimes
MIT License
1.83k stars 392 forks source link

Scaling error using passport strategy (state mismatch) #214

Closed AndTem closed 4 years ago

AndTem commented 4 years ago

Description of the problem My application is scaled using multiple replicas and the following error appears during authorization:

RPError: state mismatch, expected gsPD6U0WpmYdSXBJTE49ZF_tISh8sP4RtaTjWqtfjiw, got: pkP29wz5ICj9SELQcUwkbMMpKek_Zb8zmcfJIze0SkI

    at Client.callback (/app/node_modules/openid-client/lib/client.js:428:13)

    at /app/node_modules/openid-client/lib/passport_strategy.js:150:35

    at OpenIDConnectStrategy.authenticate (/app/node_modules/openid-client/lib/passport_strategy.js:174:5)

    at attempt (/app/node_modules/passport/lib/middleware/authenticate.js:361:16)

    at authenticate (/app/node_modules/passport/lib/middleware/authenticate.js:362:7)

    at /app/src/middlewares/oidcAuth/oidcAuthMiddleware.js:30:55

    at /app/src/utils/auth/auth.js:8:10

    at Layer.handle [as handle_request] (/app/node_modules/express/lib/router/layer.js:95:5)

    at trim_prefix (/app/node_modules/express/lib/router/index.js:317:13)

    at /app/node_modules/express/lib/router/index.js:284:7 {

Express-session is used to work with sessions. Reddis is used as storage.

Session settings

  createSession({
    store,
    secret: SESSION_SECRET,
    resave: false,
    saveUninitialized: true
  });

Possible Solution Having studied the strategy code, I realized why I get an error: the state of the oidc field is created at the beginning of authorization and placed in storage https://github.com/panva/node-openid-client/blob/ea792096834f285e1457947cc5b617bf6efeed95/lib/passport_strategy.js#L91 then when the response is generated, it deletes the oidc data from the store and saves it locally https://github.com/panva/node-openid-client/blob/ea792096834f285e1457947cc5b617bf6efeed95/lib/passport_strategy.js#L134

Thus it turns out that different replicas store different values state.

I think removing this line would solve my problem: https://github.com/panva/node-openid-client/blob/ea792096834f285e1457947cc5b617bf6efeed95/lib/passport_strategy.js#L134

panva commented 4 years ago

the state of the oidc field is created at the beginning of authorization and placed in storage then when the response is generated, it deletes the oidc data from the store and saves it locally

response is not generated, it is received by the process, and it cleans up the session namespace related to the authorization. This is intentional and not a bug.

I don't understand your issue and lack details to help. It could be anything from a bad idp to you e.g. reading from a secondary/slave rather than the primary.