Update OAuth2-Backend-Approach.md
This commit is contained in:
parent
35950a209b
commit
fdc1951170
@ -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' });
|
||||
}
|
||||
}
|
||||
});
|
||||
```
|
||||
Loading…
x
Reference in New Issue
Block a user