From 71b32b23ca3a7f30c49bb72df9fe48475d568d53 Mon Sep 17 00:00:00 2001 From: Mantas Sidlauskas Date: Tue, 6 Aug 2024 09:20:54 +0300 Subject: [PATCH] use refresh token --- server/middleware/oidc/index.js | 60 ++++++++++++++++----------------- 1 file changed, 30 insertions(+), 30 deletions(-) diff --git a/server/middleware/oidc/index.js b/server/middleware/oidc/index.js index b5ea4eb2c..c63a89f4e 100644 --- a/server/middleware/oidc/index.js +++ b/server/middleware/oidc/index.js @@ -25,9 +25,10 @@ const session = require('koa-session'); const allowUrl = ['/login', '/logout', '/oauth2/redirect']; let settings = {}; +var oiClient; try { - settings = require('../../config/oidc'); + settings = require('../../config/oidc.js'); } catch (e) { console.log('OIDC configuration file not found, using ENV variables'); } @@ -47,14 +48,14 @@ const middleware = async function(ctx, next) { return ctx.redirect('/login'); } - // logout user to remove session with old token + // refresh token when access token is expired if ( ctx.state.user.exp !== undefined && ctx.state.user.exp < Date.now() / 1000 ) { - ctx.logout(); - - return ctx.redirect('/login'); + ts = await oiClient.refresh(ctx.state.user.refreshToken); + ctx.state.user.exp = ts.expires_at + ctx.state.user.accessToken = ts.access_token } ctx.authTokenHeaders = ctx.authTokenHeaders || {}; @@ -85,38 +86,37 @@ const setupAuth = async function(app, router) { passport.deserializeUser((user, done) => done(null, user)); const discovered = await OpenIDClient.Issuer.discover(discoverURL); - const openIdClient = new discovered.Client({ + oiClient = new discovered.Client({ client_id: clientID, client_secret: clientSecret, }); - const openIDStrategy = new OpenIDClient.Strategy( - { - client: openIdClient, - params: { - redirect_uri: callbackURL, - scope: scope, - }, - passReqToCallback: false, - sessionKey: 'koa.sess', - }, - (tokenSet, user, done) => { - let email = ''; - if (tokenSet.claims().email) { - email = tokenSet.claims().email; - } - - return done(null, { - accessToken: tokenSet.access_token, - exp: tokenSet.expires_at, - email: email, - }); - } - ); +const strategyOptions = { + client: oiClient, + params: { + redirect_uri: callbackURL, + scope: scope, + }, + passReqToCallback: false, +}; - passport.use('oidc', openIDStrategy); + passport.use('oidc', OpenIDClient.Strategy(strategyOptions,verifyCallback)); }; +function verifyCallback (tokenSet, user, done) { + let email = ''; + if (tokenSet.claims().email) { + email = tokenSet.claims().email; + } + + return done(null, { + accessToken:tokenSet.access_token, + refreshToken:tokenSet.refresh_token, + exp: tokenSet.expires_at, + email: email, + }); +} + module.exports = { setupAuth: setupAuth, middleware: middleware,