From 6bd4d8918010f4f7a5070cdaa49cdb68c78ba5f7 Mon Sep 17 00:00:00 2001 From: Ste Vaidis Date: Sun, 15 Dec 2024 18:57:00 +0200 Subject: [PATCH] Update OAuth2-Front-Approach.md --- OAuth2-Front-Approach.md | 87 ++++++++++++++++++++-------------------- 1 file changed, 43 insertions(+), 44 deletions(-) diff --git a/OAuth2-Front-Approach.md b/OAuth2-Front-Approach.md index 03b11af..a3db58c 100644 --- a/OAuth2-Front-Approach.md +++ b/OAuth2-Front-Approach.md @@ -143,6 +143,49 @@ Content-Type: application/json *Security: The backend never expose the client_secret to the frontend. This step should always be handled on the backend.* +
+ +
+

Frontend Code

+ +```js +// On the backend callback URL, the frontend receives the authorization code +import { useEffect } from 'react'; +import { useRouter } from 'next/router'; + +const Callback = () => { + const router = useRouter(); + + useEffect(() => { + const { code, state } = router.query; + + // Send the authorization code to the backend for token exchange + fetch('/api/auth/exchange-token', { + method: 'POST', + body: JSON.stringify({ code }), + headers: { + 'Content-Type': 'application/json', + }, + }) + .then(response => response.json()) + .then(data => { + // Handle success (store token, update UI, etc.) + console.log(data); // Typically, you'll store the access token here or manage the user session. + router.push('/dashboard'); // Redirect the user to their dashboard or home page. + }) + .catch(error => { + console.error('Error exchanging token:', error); + }); + }, []); + + return
Loading...
; +}; + +export default Callback; +``` + +
+

HTTP POST Request from Backend to Google

@@ -233,50 +276,6 @@ app.listen(3000, () => {
- - - -
-

Frontend Code

- -```js -// On the backend callback URL, the frontend receives the authorization code -import { useEffect } from 'react'; -import { useRouter } from 'next/router'; - -const Callback = () => { - const router = useRouter(); - - useEffect(() => { - const { code, state } = router.query; - - // Send the authorization code to the backend for token exchange - fetch('/api/auth/exchange-token', { - method: 'POST', - body: JSON.stringify({ code }), - headers: { - 'Content-Type': 'application/json', - }, - }) - .then(response => response.json()) - .then(data => { - // Handle success (store token, update UI, etc.) - console.log(data); // Typically, you'll store the access token here or manage the user session. - router.push('/dashboard'); // Redirect the user to their dashboard or home page. - }) - .catch(error => { - console.error('Error exchanging token:', error); - }); - }, []); - - return
Loading...
; -}; - -export default Callback; -``` - -
-