Update OAuth2-Backend-Approach.md
This commit is contained in:
parent
f4d9a5b796
commit
cddb8b5160
@ -130,6 +130,60 @@ app.get('/auth/google/callback', async (req, res) => {
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
```js
|
||||||
|
import React, { useState, useEffect } from 'react';
|
||||||
|
import axios from 'axios';
|
||||||
|
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
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>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default App;
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user