From 584d5b19586258f41b14c6762678193dd6493201 Mon Sep 17 00:00:00 2001 From: Ste Vaidis Date: Sun, 15 Dec 2024 12:31:42 +0200 Subject: [PATCH] Update OAuth2.md --- OAuth2.md | 69 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) diff --git a/OAuth2.md b/OAuth2.md index 1015254..07405f7 100644 --- a/OAuth2.md +++ b/OAuth2.md @@ -33,6 +33,8 @@ A way for the `user` to tell `google` to give an access token to `xorismesiti.gr + + # 1. [Frontend] Request Authorization code 1. The use clicks a "Login with Google" button with a URL to Google's OAuth 2.0 authorization endpoint and redirects the user there. @@ -82,12 +84,29 @@ const loginWithGoogle = () => { + + # 2. [Frontend] Receive Authorization Code 1. User grants permission 2. Google redirect the user to the `redirect_uri` you specified in the previous request (`https://xorismesiti.gr/api/auth/callback`) 3. The frontend must not directly exchange the `code` for an `access_token`. Instead, it sends the `code` to the backend via an API request. + +
+

HTTP Request

+ +```bash +POST https://xorismesiti.gr/api/auth/exchange-token +Content-Type: application/json + +{ + "code": "authorization-code-from-google" +} +``` + +
+

Frontend Code

@@ -133,6 +152,8 @@ export default Callback; + + # 3. Backend (Node.js): Handle Token Exchange 1. The backend receives the authorization `code` from the frontend, @@ -167,6 +188,21 @@ client_secret=YOUR_GOOGLE_CLIENT_SECRET
+
+

HTTP Response

+ +```json +{ + "access_token": "ya29.a0AfH6SMC8Op6zXZkHi2XITkDoOVzYXt3hTY6sny54UlWlxrnKlX5Xv78is7BEHekVX-VoA", + "token_type": "Bearer", + "expires_in": 3600, + "refresh_token": "1//04d5XHqmn6Hdy3wTf5OYDP1SyBa74zEFURjddQ2A1cFw78PY13pQyWhlD2A6XhDQtKlrjAqU4kS3vGdMvckw", + "scope": "email profile" +} +``` + +
+

Example Backend Code:

@@ -219,12 +255,45 @@ app.listen(3000, () => { + + # 4. [Frontend] Use the Access Token Once the backend exchanges the `code` for the `access_token`, the frontend can use it to make authenticated requests to the backend or Google APIs + + +
+

HTTP Request

+ +```bash +GET https://xorismesiti.gr/api/user-profile +Authorization: Bearer access-token-from-backend +``` + +
+ +
+

HTTP Response

+ +```json +{ + "sub": "1234567890", + "name": "John Doe", + "given_name": "John", + "family_name": "Doe", + "profile": "https://plus.google.com/1234567890", + "picture": "https://lh3.googleusercontent.com/a-/AOh14GgIXXl5JXzW0c1Szbl-e1Jch1vhl5rHhH65vlK6J5g5PqkGjj1O0p3t8bgVEOykQ6ykFSQ=s96", + "email": "john.doe@example.com", + "email_verified": true, + "locale": "en" +} +``` + +
+

Example Frontend Code: