{"id":31783940,"url":"https://github.com/diixo/google-oauth2-integration-with-fastapi","last_synced_at":"2025-10-10T10:58:00.676Z","repository":{"id":293763884,"uuid":"984974795","full_name":"diixo/Google-OAuth2-integration-with-FastAPI","owner":"diixo","description":"Google OAuth2 integration with FastAPI","archived":false,"fork":false,"pushed_at":"2025-06-21T15:18:28.000Z","size":20206,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-06-21T16:27:12.580Z","etag":null,"topics":["fastapi","google-oauth2"],"latest_commit_sha":null,"homepage":"","language":"HTML","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/diixo.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2025-05-16T20:46:31.000Z","updated_at":"2025-06-21T15:18:31.000Z","dependencies_parsed_at":"2025-06-14T03:30:03.831Z","dependency_job_id":null,"html_url":"https://github.com/diixo/Google-OAuth2-integration-with-FastAPI","commit_stats":null,"previous_names":["diixo/google-oauth-integration-with-fastapi","diixo/google-oauth2-integration-with-fastapi"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/diixo/Google-OAuth2-integration-with-FastAPI","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/diixo%2FGoogle-OAuth2-integration-with-FastAPI","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/diixo%2FGoogle-OAuth2-integration-with-FastAPI/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/diixo%2FGoogle-OAuth2-integration-with-FastAPI/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/diixo%2FGoogle-OAuth2-integration-with-FastAPI/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/diixo","download_url":"https://codeload.github.com/diixo/Google-OAuth2-integration-with-FastAPI/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/diixo%2FGoogle-OAuth2-integration-with-FastAPI/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":279003564,"owners_count":26083595,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-10-10T02:00:06.843Z","response_time":62,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["fastapi","google-oauth2"],"created_at":"2025-10-10T10:57:58.756Z","updated_at":"2025-10-10T10:58:00.669Z","avatar_url":"https://github.com/diixo.png","language":"HTML","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Google-OAuth2-integration-with-FastAPI\n\nBackend for [chrome-ext](https://github.com/diixo/chrome-ext)\n\n\nRun **django** server:\n```bash\npy core/manage.py runserver\n```\n\n\n### Environments:\n\nCreate `server/.env` that looks like:\n```bash\nGOOGLE_CLIENT_ID=\u003cyour-google-client-id\u003e\nGOOGLE_CLIENT_SECRET=\u003cyour-google-client-secret\u003e\nSECRET_KEY = \"web-app-secret-key\"\nREDIRECT_URL = \"http://127.0.0.1:8001/auth\"\nFRONTEND_URL = \"http://127.0.0.1:8001/auth\"\nJWT_SECRET_KEY = \"your-jwt-secret-key\"\n```\n\n\n## Requirements:\n\n```bash\nauthlib\nfastapi\ngoogle-auth\nitsdangerous\npyjwt\npython-jose[cryptography]\npython-dotenv\nrequests\nsqlalchemy\nuvicorn\n```\n\nDependency on httpx\u003e=0.23:\n```bash\npip install httpx==0.27.2\npip install pydantic==1.10.22\n```\n\nCheck:\n```bash\npip install sqlalchemy==2.0.24\npip install fastapi==0.103.2\n```\n\n\n## Google Authentication OAuth2:\n\n* `Регистрируем в Google Cloud Console расширение как WebApplication, получаем CLIENT_ID` (or download as json)\n\n* Вы на клиенте (расширение или сайт) открываете страницу авторизации Google.\n\n* Google спрашивает, проверяет разрешение и отдаёт авторизационный код.\n\n* Вы отправляете этот код на ваш сервер.\n\n* Сервер обменивает код на access_token и id_token (в котором есть email, имя и т.п.).\n\n* Сервер сохраняет JWT (или сессию) в БД, и кладёт в cookie (token).\n\n* Сервер возвращает токен, creds в RedirectResponse на адрес, в наше случае полученный от **chrome.identity.getRedirectURL(\"provider_cb\")** прокинутый через сессию (либо возврат на welcome-страницу, либо на Google redirect_url с токеном)\n\n\n## Routing of Working process\n\n#### 1. Генерируем JWT-токен при авторизации\nВ момент успешной авторизации, например через Google OAuth:\n\n* создаём **JWT-токен с помощью jwt.encode(...)**\n\n* отдаём его клиенту через Response\n\n\n#### 2. Запросы на fastAPI\nКогда браузерное расширение делает запросы к серверу (например, **fetch('/save-selection')**), скрипт автоматически прикрепляет к этим запросам token, используя `headers`\n\n* Извлекается клиентом (расширением) локально сохранённый токен, полученный от сервера\n\n* Предварительно проверяется `expiresAt` перед отправкой\n```javascript\nmethod: 'POST',\nheaders: {\n    'Content-Type': 'application/json',\n    'Authorization': `Bearer ${stored.token}`,\n}\n```\n\n\n#### 3. Проверка и валидация запросов\n\n* Сервер валидирует токен\n\nПример на fastAPI эндпоинте:\n```python\n@app.post(\"/save-selection\")\nasync def save_selection(data: SelectionData, current_user: dict = Depends(get_current_user)):\n```\n\n* берёт token из `headers` запроса - с помощью get_current_user_header (get_current_user версия для куки)\n\n* декодирует его через **jwt.decode(...)**\n\n* извлекает **user_id**, **email** и т.д.\n\n* если всё ок — передаёт эти данные в эндпоинт\n\n\n## References:\n\n* [integrating-google-authentication-with-fastapi-a-step-by-step-guide](https://blog.futuresmart.ai/integrating-google-authentication-with-fastapi-a-step-by-step-guide) + [Full Code in GitHub](https://github.com/PradipNichite/FutureSmart-AI-Blog/tree/main/Google%20OAuth%20Integration%20with%20FastAPI)\n\n\n## Examples:\n\n* https://medium.com/@vivekpemawat/enabling-googleauth-for-fast-api-1c39415075ea\n* https://parlak-deniss.medium.com/fastapi-authentication-with-google-oauth-2-0-9bb93b784eee\n* https://blog.hanchon.live/guides/google-login-with-fastapi/\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdiixo%2Fgoogle-oauth2-integration-with-fastapi","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdiixo%2Fgoogle-oauth2-integration-with-fastapi","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdiixo%2Fgoogle-oauth2-integration-with-fastapi/lists"}