From fdc19511701479134971558dc8ae855eddcd01e6 Mon Sep 17 00:00:00 2001 From: Ste Vaidis Date: Wed, 8 Jan 2025 10:19:52 +0200 Subject: [PATCH] Update OAuth2-Backend-Approach.md --- OAuth2-Backend-Approach.md | 61 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) diff --git a/OAuth2-Backend-Approach.md b/OAuth2-Backend-Approach.md index e3d5ea8..1e5230e 100644 --- a/OAuth2-Backend-Approach.md +++ b/OAuth2-Backend-Approach.md @@ -322,3 +322,64 @@ app.get('/api/dashboard-data', (req, res) => { } }); ``` + + +# Refresh token + +```js +app.get('/api/dashboard-data', async (req, res) => { + const authToken = req.cookies.auth_token; + const refreshToken = await getRefreshTokenFromDB(); // Get from your DB + + try { + // + // If the token is still valid + // + const userData = verifyToken(authToken); + const dashboardData = await getDashboardData(userData); + res.json(dashboardData); + } catch (err) { + if (err.name === 'TokenExpiredError') { + try { + // + // Get new tokens using refresh token + // + const response = await fetch('https://oauth2.googleapis.com/token', { + method: 'POST', + body: JSON.stringify({ + refresh_token: refreshToken, + client_id: CLIENT_ID, + client_secret: CLIENT_SECRET, + grant_type: 'refresh_token' + }) + }); + + const { access_token } = await response.json(); + + // + // Set new cookie with new access token + // + res.cookie('auth_token', access_token, { + httpOnly: true, + secure: true, + sameSite: 'strict' + }); + + // + // Continue with the original request using new token + // + const userData = verifyToken(access_token); + const dashboardData = await getDashboardData(userData); + res.json(dashboardData); + } catch (refreshError) { + // + // If refresh fails, user needs to login again + // + res.status(401).json({ error: 'Session expired' }); + } + } else { + res.status(401).json({ error: 'Invalid token' }); + } + } +}); +``` \ No newline at end of file