From f8e2ab65db114dc5a5fc38bbf13d359f333c5e05 Mon Sep 17 00:00:00 2001 From: Ste Vaidis Date: Sun, 15 Dec 2024 18:09:31 +0200 Subject: [PATCH] Update OAuth2-Front-Approach.md --- OAuth2-Front-Approach.md | 82 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 80 insertions(+), 2 deletions(-) diff --git a/OAuth2-Front-Approach.md b/OAuth2-Front-Approach.md index 974da73..04b551a 100644 --- a/OAuth2-Front-Approach.md +++ b/OAuth2-Front-Approach.md @@ -363,11 +363,89 @@ const fetchUserData = async (accessToken) => {


+# 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 + +
+

Frontend HTTP GET Request to Google

+ +```bash +GET https://www.googleapis.com/oauth2/v3/userinfo +Authorization: Bearer ACCESSTOKEN6zXZkHi2XITkDoOVACCESSTOKEN +``` + +
+ +
+

Google HTTP Response to Frontend

+ +```json +{ + "error": "invalid_token", + "error_description": "The access token expired" +} +``` + +
+
+

Frontend HTTP POST Refresh token to Backend

+ +```bash + +``` + +
+ +
+

Frontend Code

+ +```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); + } +}; +``` + +
+
+

Frontend Code

+```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 +``` +