Update OAuth2-Front-Approach.md
This commit is contained in:
parent
2778a26ef1
commit
f8e2ab65db
@ -363,11 +363,89 @@ const fetchUserData = async (accessToken) => {
|
||||
<br><br><br>
|
||||
|
||||
|
||||
# 5. [Frontend] Refresh the Token
|
||||
|
||||
If the access token is expired, the frontend will receive an error response from Google when attempting to fetch user data
|
||||
|
||||
<details>
|
||||
<summary><h3>Frontend HTTP GET Request to Google</h3></summary>
|
||||
|
||||
```bash
|
||||
GET https://www.googleapis.com/oauth2/v3/userinfo
|
||||
Authorization: Bearer ACCESSTOKEN6zXZkHi2XITkDoOVACCESSTOKEN
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><h3>Google HTTP Response to Frontend</h3></summary>
|
||||
|
||||
```json
|
||||
{
|
||||
"error": "invalid_token",
|
||||
"error_description": "The access token expired"
|
||||
}
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
|
||||
<details>
|
||||
<summary><h3>Frontend HTTP POST Refresh token to Backend</h3></summary>
|
||||
|
||||
```bash
|
||||
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><h3>Frontend Code</h3></summary>
|
||||
|
||||
```js
|
||||
const refreshAccessToken = async (refreshToken) => {
|
||||
try {
|
||||
const response = await fetch('/api/refresh-token', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ refresh_token: refreshToken }),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to refresh access token');
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
return data.access_token; // New access token
|
||||
} catch (error) {
|
||||
console.error('Error refreshing access token:', error);
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
|
||||
<details>
|
||||
<summary><h3>Frontend Code</h3></summary>
|
||||
|
||||
```js
|
||||
const response = await fetch('https://oauth2.googleapis.com/token', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
},
|
||||
body: new URLSearchParams({
|
||||
client_id: 'YOUR_GOOGLE_CLIENT_ID',
|
||||
client_secret: 'YOUR_GOOGLE_CLIENT_SECRET',
|
||||
refresh_token: refreshToken,
|
||||
grant_type: 'refresh_token',
|
||||
}),
|
||||
});
|
||||
|
||||
|
||||
|
||||
const data = await response.json();
|
||||
const newAccessToken = data.access_token; // New access token
|
||||
```
|
||||
</details>
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user