Update OAuth2-Backend-Approach.md

This commit is contained in:
Ste Vaidis 2025-01-08 09:55:53 +02:00
parent 55ab14313b
commit 99d9ead65a

View File

@ -178,10 +178,11 @@ app.get('/callback', async (req, res) => {
sameSite: 'strict', // CSRF protection
maxAge: 24 * 60 * 60 * 1000, // 24 hours
});
res.redirect('https://myapp/authentication-success');
res.redirect('https://myapp/dashboard');
} catch (error) {
res.redirect('https://myapp/authentication-error');
res.redirect('https://myapp/login');
}
});
```
@ -248,54 +249,76 @@ curl -X GET "https://www.googleapis.com/oauth2/v3/userinfo" \
### Frontend Code
```js
import React, { useState, useEffect } from 'react';
import axios from 'axios';
// DashboardPage.jsx
import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
const App = () => {
const [user, setUser] = useState(null);
const [isAuthenticated, setIsAuthenticated] = useState(false);
// Fetch user data from the backend's /profile endpoint
const fetchUserData = async () => {
try {
const response = await axios.get('http://localhost:3000/profile', {
withCredentials: true, // Important: Ensure cookies are sent with the request
});
setUser(response.data); // Set the user data from the response
setIsAuthenticated(true);
} catch (error) {
console.error('Error fetching user profile:', error);
}
};
function DashboardPage() {
const navigate = useNavigate();
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState(null);
const [dashboardData, setDashboardData] = useState(null);
useEffect(() => {
// Check if the user is authenticated by checking the cookie
if (document.cookie.includes('access_token')) {
fetchUserData(); // Fetch user profile if the access token is available in cookies
async function initializeDashboard() {
try {
//
// First verify auth
//
const authResponse = await fetch('https://myapp/api/verify-auth', {
credentials: 'include',
});
if (!authResponse.ok) {
throw new Error('Authentication failed');
}
//
// Auth is valid, now fetch dashboard data
//
const dataResponse = await fetch('https://myapp/api/dashboard-data', {
credentials: 'include',
});
if (!dataResponse.ok) {
throw new Error('Failed to load dashboard data');
}
const data = await dataResponse.json();
setDashboardData(data);
setIsLoading(false);
} catch (err) {
//
// Redirect to login on auth failure
//
setError(err.message);
navigate('/login');
}
}
}, []);
initializeDashboard();
}, [navigate]);
if (isLoading) {
return (
<div className="flex items-center justify-center min-h-screen">
<div className="text-center">
<h2>Loading Dashboard...</h2>
<p>Please wait while we verify your session.</p>
</div>
</div>
);
}
if (error) {
return null;
}
return (
<div className="App">
<h1>Google OAuth2 with React</h1>
{!isAuthenticated ? (
<div>
<p>Please log in with Google to access your profile:</p>
<button onClick={() => window.location.href = 'http://localhost:3000/auth/google'}>
Login with Google
</button>
</div>
) : (
<div>
<h2>Welcome, {user?.name}</h2>
<p>Email: {user?.email}</p>
<img src={user?.picture} alt="Profile" />
</div>
)}
<div>
<h1>Welcome to Dashboard</h1>
</div>
);
};
export default App;
}
```