panva / openid-client

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

How to use without a session, save token/user in normal cookie? #139

Closed LocalMagic closed 5 years ago

LocalMagic commented 5 years ago

Im not too experienced with passportjs but we currently use openid-client with cookie-session.

However we would like to try and move away from sessions and just store either a simple cookie with a token, or attach the token to a header on each request which we then introspect to see whether the token is valid.

I can't figure it out, maybe it's not possible, I just simply don't know where or how I can retrieve the token from the library, and when and how I should save it in a cookie. Maybe it is only built to use a session.

currently we have:


         passport.use(
        `oidc.${site}`,
        new Strategy(
          {
            client,
            params: getParamsForSite(site),
            passReqToCallback,
            usePKCE,
          },
          (tokenset, done) => {
            const user = {
              token: tokenset,
              name: tokenset.claims.sub,
            };

            return done(null, user);
          }
        )
      );

then

    app.get(['/login', '/login/:site'], (req, res, next) => {
  if (req.params.site) {
    passport.authenticate(`oidc.${req.params.site}`)(req, res, next);
  } else {
    res.end(loginFrontend.success());
  }
});

and for the callback

        app.get('/auth_callback', (req, res, next) => {
      passport.authenticate(`oidc.${req.query.state}`, {
        callback: true,
        successReturnToOrRedirect: process.env.BASE_URI,
      })(req, res, next);
    });

We would like to continue using this library as the authentication service we call has a discovery endpoint etc. and wouldn't want to implement all of the features ourselves. If I set session to false, how do I retrieve the token and where for this strategy, can someone help me?

panva commented 5 years ago

Hi @LocalMagic,

the strategy needs a session mechanism to work (it saves states, nonces, etc to be able to verify callbacks for you).

The rest is really a passport question (i mean, not saving a user but rather the token) and you should be able to define this by just specifying the serializeUser / deserializeUser functions of passport.

In all of this, the actual session mechanism is up to you to choose (if it's cookie-session or smth else), it doesn't matter