So I'm trying to save an access token to the state within Koa, just for use later and saving having to pass it around the client.
Following the passport oauth2 documentation for Koa, I'm struggling to persist anything to ctx.state
...
Koa / passport oauth2 setup:
server.koaApp.use(koaSession(
{
key: sessionKey,
rolling: true,
maxAge: sessionMaxAge,
sameSite: 'none',
secure: true,
// @ts-ignore
domain: undefined
},
server.koaApp,
));
// set up passport sessions here
function createPassport() {
const passport = new KoaPassport();
passport.use(new OAuth2Strategy({
authorizationURL: oauthClientAuthUrl,
tokenURL: oauthClientTokenUrl,
clientID: oauthClientId,
clientSecret: oauthClientSecret,
callbackURL: oauthClientRedirectUrl,
}, function(accessToken, refreshToken, params, profile, cb) {
cb(null, {id: 'somedudesID', accessToken});
}));
passport.serializeUser((user, done) => {
done(null, user);
});
passport.deserializeUser((user, done) => {
done(null, user);
});
return passport;
};
Route declarations that should set and read accesstoken:
router.get('/authorize', passport.authenticate('oauth2'), (ctx: any) => {
const { accessToken } = ctx.session.passport.user;
ctx.state.accessToken = accessToken;
ctx.status = 200;
});
router.get('/get-token-from-state', (ctx: any) => {
console.log(ctx.state.accessToken); // undefined
});
Questions:
Why is
ctx.state.accessToken
undefined when doing a get to/get-token-from-state
?Should I even be trying to persist the access token like this? Is there another way to obtain the accessToke in other routes?
ctx.state
orctx.session
. Logs: ctx.state = { _passport: { instance: KoaPassport { _key: 'passport', _strategies: [Object], _serializers: [Array], _deserializers: [Array], _infoTransformers: [], _framework: [Object], _userProperty: 'user', _sm: [SessionManager] } } } ctx.session = { cookie: { httpOnly: true, path: '/', overwrite: true, signed: true, maxAge: 86400000 } } – Enyo