Update OAuth2-Backend-Approach.md

This commit is contained in:
Ste Vaidis 2025-01-08 10:24:59 +02:00
parent fdc1951170
commit c0e47399d5

View File

@ -121,19 +121,14 @@ Location: http://localhost:3000/dashboard
Set-Cookie: access_token=ya29.a0AfH6SMC8Op6zkVX-VoA; HttpOnly; Secure; Max-Age=3600; Path=/;
```
<details>
<summary>
<h4>Backend code</h4>
<br><br>
Implements the endpoint /auth/google/callback
<br><br>
<p>1. Recieves authorization code from Google</p><br>
<p>2. POST send the authorization code to https://oauth2.googleapis.com/token</p><br>
<p>3. POST response the access & refresh tokens</p><br>
<p>4. Redirect to Fronend success page with a cookie contains the access token</p><br>
</summary>
### Backend code
<br><br>
Implements the endpoint /auth/google/callback
1. Recieves authorization code from Google
2. POST send the authorization code to https://oauth2.googleapis.com/token
3. POST response the access & refresh tokens
4. Redirect to Fronend success page with a cookie contains the access token
```js
app.get('/callback', async (req, res) => {
@ -303,28 +298,15 @@ function DashboardPage() {
### Backend Dashboard
```js
app.get('/api/dashboard-data', (req, res) => {
// The auth cookie is automatically included in req.cookies
const authToken = req.cookies.auth_token;
If the token is valid send the data.
if (!authToken) {
return res.status(401).json({ error: 'Not authenticated' });
}
If the token is not valid:
// Verify the token and get data in one go
try {
// verify token...
// get dashboard data...
res.json({ dashboardData: 'your data here' });
} catch (err) {
res.status(401).json({ error: 'Invalid token' });
}
});
```
1. Get new tokens using refresh token
2. Set new cookie with new access token
3. Continue with the original request using new token
# Refresh token
or login again
```js
app.get('/api/dashboard-data', async (req, res) => {
@ -342,7 +324,7 @@ app.get('/api/dashboard-data', async (req, res) => {
if (err.name === 'TokenExpiredError') {
try {
//
// Get new tokens using refresh token
// 1. Get new tokens using refresh token
//
const response = await fetch('https://oauth2.googleapis.com/token', {
method: 'POST',
@ -357,7 +339,7 @@ app.get('/api/dashboard-data', async (req, res) => {
const { access_token } = await response.json();
//
// Set new cookie with new access token
// 2. Set new cookie with new access token
//
res.cookie('auth_token', access_token, {
httpOnly: true,
@ -366,7 +348,7 @@ app.get('/api/dashboard-data', async (req, res) => {
});
//
// Continue with the original request using new token
// 3. Continue with the original request using new token
//
const userData = verifyToken(access_token);
const dashboardData = await getDashboardData(userData);