Update OAuth2.md

This commit is contained in:
Ste Vaidis 2024-12-15 15:15:42 +02:00
parent f374f492ac
commit 24dcb6791c

View File

@ -463,9 +463,18 @@ Authorization: Bearer ya29.a0AfH6SMC8Op6zXZkHi2XITkDoOVzYXt3hTY6sny54UlWlxrnKlX5
<summary><h3>Backend GET Code</h3></summary> <summary><h3>Backend GET Code</h3></summary>
```js ```js
app.get('/api/user-profile', async (req, res) => { const express = require('express');
const accessToken = req.headers['authorization'].split(' ')[1]; // Extract token from Authorization header const axios = require('axios');
const app = express();
app.use(express.json()); // To parse JSON bodies
const clientId = 'YOUR_GOOGLE_CLIENT_ID'; // Google Client ID
const clientSecret = 'YOUR_GOOGLE_CLIENT_SECRET'; // Google Client Secret
const redirectUri = 'https://xorismesiti.gr/api/auth/callback'; // Must match the one used in frontend
// Function to validate the access token by making a request to the Google user info endpoint
const validateAccessToken = async (accessToken) => {
try { try {
const response = await axios.get('https://www.googleapis.com/oauth2/v3/userinfo', { const response = await axios.get('https://www.googleapis.com/oauth2/v3/userinfo', {
headers: { headers: {
@ -473,17 +482,75 @@ app.get('/api/user-profile', async (req, res) => {
}, },
}); });
// Send the user profile data to the frontend // If this succeeds, the token is valid
res.json(response.data); return response.data; // Return the user data
} catch (error) { } catch (error) {
console.error('Error fetching user profile:', error); // If the request fails (token is invalid or expired), throw an error
res.status(500).json({ error: 'Failed to fetch user profile' }); throw new Error('Invalid or expired access token');
} }
};
// Example route for fetching the user profile
app.get('/api/user-profile', async (req, res) => {
const accessToken = req.headers['authorization']?.split(' ')[1]; // Extract token from Authorization header
if (!accessToken) {
return res.status(400).json({ error: 'No access token provided' });
}
try {
// Validate the access token by fetching user info from Google
const userData = await validateAccessToken(accessToken);
// Send the user profile data to the frontend
res.json(userData);
} catch (error) {
// Handle invalid or expired token
console.error('Error validating access token:', error);
res.status(401).json({ error: 'Invalid or expired access token' });
}
});
// Start the server
app.listen(3000, () => {
console.log('Server running on http://localhost:3000');
}); });
``` ```
</details> </details>
<details>
<summary><h3>Front GET Code</h3></summary>
```js
// After receiving the token, store it in the frontend (e.g., localStorage or context)
localStorage.setItem('access_token', response.access_token);
// Use it to make authenticated API requests to the backend
fetch('/api/user-profile', {
headers: {
'Authorization': `Bearer ${localStorage.getItem('access_token')}`,
},
})
.then(response => {
if (response.status === 401) {
// Handle token expiration or invalid token
console.error('Access token expired or invalid. Please log in again.');
// Optionally, redirect to login page or refresh token
} else {
return response.json();
}
})
.then(data => {
// Handle user data
console.log(data);
})
.catch(error => {
console.error('Error fetching user profile:', error);
});
```
</details>
<br><br><br> <br><br><br>