惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

D
DataBreaches.Net
T
The Exploit Database - CXSecurity.com
V
Vulnerabilities – Threatpost
Know Your Adversary
Know Your Adversary
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
N
News and Events Feed by Topic
Spread Privacy
Spread Privacy
Application and Cybersecurity Blog
Application and Cybersecurity Blog
S
Secure Thoughts
G
GRAHAM CLULEY
Google Online Security Blog
Google Online Security Blog
Help Net Security
Help Net Security
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
O
OpenAI News
Google DeepMind News
Google DeepMind News
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
Security Archives - TechRepublic
Security Archives - TechRepublic
L
LINUX DO - 最新话题
Microsoft Azure Blog
Microsoft Azure Blog
C
Cybersecurity and Infrastructure Security Agency CISA
Stack Overflow Blog
Stack Overflow Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
L
Lohrmann on Cybersecurity
H
Hacker News: Front Page
W
WeLiveSecurity
P
Privacy International News Feed
Forbes - Security
Forbes - Security
月光博客
月光博客
PCI Perspectives
PCI Perspectives
T
Tailwind CSS Blog
N
News and Events Feed by Topic
T
Threat Research - Cisco Blogs
Engineering at Meta
Engineering at Meta
F
Full Disclosure
AI
AI
Hacker News - Newest:
Hacker News - Newest: "LLM"
Schneier on Security
Schneier on Security
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
B
Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
D
Darknet – Hacking Tools, Hacker News & Cyber Security
V
Visual Studio Blog
The Hacker News
The Hacker News
博客园 - 叶小钗
G
Google Developers Blog
Google DeepMind News
Google DeepMind News
博客园 - 司徒正美
T
The Blog of Author Tim Ferriss

StudyingLover's Blog

Diffusion Policy笔记 rwkv笔记 act笔记 nanovllm-block_manager opencode多智能体 nanobot-pre-train nanobot-rl nanobot-sft nanobot-checkpoint_manager nanobot-gpt nanobot-mid-train Vision Mamba (Vim)笔记 BPE演示 最后一遍学习Transformer YOLOv5 目标检测笔记 下载根服务器解析记录 Dynaseal A Backend-Controlled LLM API Key Distribution Scheme with Constrained Invocation Parameters 判断链表有环 王道25数据结构勘误 关于perplexity的open-sourcing-r1-1776 AI为什么不像人类一样进行多轮对话 新博客改造日记和功能测试 linuxqq只显示登陆背景图 数字设计和计算机体系结构(机械工业出版社)勘误(自制) Dynaseal:面向未来端侧llm agent的llm api key分发机制 A Definitive Guide to Markdown Style This post is using MDX, Where you can embed JSX and Astro components RT-Patch学习 pydantic实现的LLM ReAct fastapi 和 uvicorn 设置监听 ipv6 pydantic+openai+json 控制大模型输出的最佳范式 解决 Matplotlib Scatter 不支持 Marker 列表的问题:mscatter 实现 roofline model zhipuAI接口兼容openai 在docker部署fastapi宝塔里使用nginx反代套上cloudflare获取请求的真实ip clion搭建libbpf-bootstrap开发环境 coze+coze-discord-proxy+ChatNextWebUI实现AI自由 安卓内核时间使用的是UTC时间 colab运行google最新开源模型Gemma Sora技术报告 视频生成模型作为世界模拟器 笔记 archlinux flutter开发踩坑 linux下NTFS磁盘报错输入输出错误 Venn-Abers 预测器 基于Venn-Abers预测器的系统日志异常检测方法_顾兆军 手机平板远程访问kvm虚拟机的windows phi-2弱智吧测评 poe的gemini pro或是百度开发 google gemini api使用 google gemini api申请 构建用于复杂数据处理的高效UDP服务器和客户端 matplotlib中文字体渲染 TruFor笔记和代码复现 深入分析:GitHub Trending 项目 "multipleWindow3dScene" pua大模型 ggml教程|mnist手写体识别量化推理 xgboost2.0最佳实践 xgboost使用GPU最佳实践 马踏棋盘 cloudlflare推理llama2 docker搭建elasticsearch并使用python连接 FreeU-文字生成图片的免费午餐笔记 使用xgboost的c接口推理模型 Archlinux使用CMake调用xgboost的c接口 m2cgen生成机器学习c语言推理代码 xgboost模型序列化存储并推理 speculative-sampling笔记 prompt2model笔记 RoboTAP笔记 自建obsidian同步服务 MediaPipe即将推出图像生成服务 Dual-Stream Diffusion Net for Text-to-Video Generation笔记 ViT在DDPM取代UNet(DiT) arch4edu搞崩了我的flutter LISA(推理分割)笔记 在终端绘制GPU显存使用曲线 GPTBot介绍 arch蓝牙无法连接 GPU部署llama-cpp-python(llama.cpp通用) 花式求GCD 使用llama构建一个蜜罐(前端) 使用llama构建一个蜜罐(后端) llama-cpp-python快速上手 快速上手llama2.c(更新版) Paper Gestalt笔记 DINO-v2笔记 快速上手llama2.c AnyDoor笔记 Archlinux安装scrcpy加载共享库出错 error while loading shared libraries:libusb-1.0.so.0:wrong ELF class:ELFCLASS32 npc_gzip笔记 python调用c++函数 Filesystem type ntfs3,ntfs not configured in kernel open_clip编码图像和文本 PicGo配置CloudflareR2图片储存 ArchlinuxGnome快捷键打开终端 clip-interrogator代码解析 GroundingDINO安装报错解决 2023华为鲲鹏畅想日暨西安高新国际会议中心零食午饭测评 RoboMaster开源仓库汇总(长期更新) 没有手都可以在腾讯云创建镜像 I3D笔记
fastapi集成google auth登录
About the Author StudyingLover · 2024-01-21 · via StudyingLover's Blog

fastapi集成google auth登录

流程设计

1. 启动 Google 登录流程

  • 前端:用户点击 Google 登录按钮。
  • 请求:前端发起请求到 /user/login/google

2. 后端处理 /user/login/google 请求

  • 后端生成一个重定向到 Google 认证服务器的 URL
  • 后端将此 URL 发送给前端。

3. 前端重定向

  • 前端接收到 URL 后,重定向用户到 Google 的登录页面。

4. 用户登录并授权

  • 用户在 Google 页面上授权你的应用。

5. Google 重定向回你的应用

  • Google 将用户重定向回你的应用,并在查询参数中附加一个授权码(code)。

6. 前端发送授权码

  • 前端:捕获此授权码并发送到 /user/auth/google?code=${code}
  • 请求POST /user/auth/google?code=${code}

7. 后端处理 /user/auth/google?code=${code} 请求

  • 后端接收授权码,并使用它向 Google 请求访问令牌。
  • 使用此令牌,后端可以从 Google 获取用户信息(如用户名、邮箱等)。
  • 后端检查此用户是否已在数据库中。如果不在,创建一个新用户。
  • 后端生成一个会话或令牌(如 JWT),并将其发送回前端。

8. 前端接收令牌

  • 前端接收令牌并存储在本地(如 localStorage、sessionStorage 或 cookie 中)。

9. 前端使用令牌

  • 对于后续请求,前端将此令牌附加到请求的授权头中,以验证用户身份。

10. 后端验证令牌

  • 对于需要身份验证的后续请求,后端验证传入的令牌,以确认用户的身份。

获取google密钥

创建项目

首先前往Google Cloud Console ( https://console.cloud.google.com/ ) 并创建一个新项目(如果尚未创建),然后在“API 和服务 > 仪表板”部分中启用“Google+ API”。你会在这样一个界面。

image.png

如果找不到的话,请先找到初始页面,选择一个项目,然后你会看到这样一个页面image.png

创建OAuth权限

按照如图顺序点击 image.png

进入之后就到了前面的页面,然后点击 OAuth权限请求页面

image.png 接下来我们会进入注册应用界面,首先填入的应用名称还有你的邮箱 image.png 在最下面填上你的开发者信息,保存并继续 image.png

一路向下,可以填入一些限制,我就直接继续了。下面添加测试用户,填入google账号的邮箱即可 image.png 保存,在摘要再检查一遍以后保存创建即可。接下来你会看到这样的页面,这样子我们的OAuth就设置好了。 image.png

创建凭据

我们下面创建应用,点击凭据 image.png 点击创建凭据 image.png 选择OAuth客户端ID image.png

选择应用类型web应用 image.png

填写名称,已获授权的 JavaScript 来源,已获授权的重定向 URI。已获授权的 JavaScript 来源 写的是你的开发,测试还有正式环境的域名,例如http://localhost:8000。已获授权的重定向 URI 写的是你的重定向地址例如http://localhost:8000/user/auth/google

image.png

你会看到这样一个页面,保存你的客户端 ID和客户端密钥 image.png

代码实践

创建一个.env文件 image.png

我们创建一个fastapi的后端

from fastapi import FastAPI, Depends
from fastapi.security import OAuth2PasswordBearer
from fastapi.middleware.cors import CORSMiddleware

import requests
from jose import jwt
import os
from dotenv import load_dotenv

load_dotenv()


app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # Allows all origins
    allow_credentials=True,
    allow_methods=["*"],  # Allows all methods
    allow_headers=["*"],  # Allows all headers
)


# Replace these with your own values from the Google Developer Console
GOOGLE_CLIENT_ID = os.environ.get("GOOGLE_CLIENT_ID")
GOOGLE_CLIENT_SECRET = os.environ.get("GOOGLE_CLIENT_SECRET")
GOOGLE_REDIRECT_URI = "http://localhost:8000/auth/google"


@app.get("/login/google")
async def login_google():
    return {
        "url": f"https://accounts.google.com/o/oauth2/auth?response_type=code&client_id={GOOGLE_CLIENT_ID}&redirect_uri={GOOGLE_REDIRECT_URI}&scope=openid%20profile%20email&access_type=offline"
    }

@app.get("/auth/google")
async def auth_google(code: str):
    token_url = "https://accounts.google.com/o/oauth2/token"
    data = {
        "code": code,
        "client_id": GOOGLE_CLIENT_ID,
        "client_secret": GOOGLE_CLIENT_SECRET,
        "redirect_uri": GOOGLE_REDIRECT_URI,
        "grant_type": "authorization_code",
    }
    response = requests.post(token_url, data=data)
    access_token = response.json().get("access_token")
    user_info = requests.get("https://www.googleapis.com/oauth2/v1/userinfo", headers={"Authorization": f"Bearer {access_token}"})
    print(user_info.json())
    return user_info.json()

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)

同时我们需要一个前端,这里我们只有一个按钮来用于google登陆

<!DOCTYPE html>
<html>
<head>
    <title>Login with Google</title>
    <script>
        async function handleLogin() {
            const response = await fetch('http://localhost:8000/login/google');
            const data = await response.json();
            window.location.href = data.url;
        }

        async function handleRedirect() {
            const urlParams = new URLSearchParams(window.location.search);
            const code = urlParams.get('code');
            if (code) {
                const response = await fetch(`http://localhost:8000/auth/google?code=${code}`);
                const userData = await response.json();
                document.getElementById('user-info').textContent = JSON.stringify(userData, null, 2);
            }
        }
    </script>
</head>
<body onload="handleRedirect()">
    <button onclick="handleLogin()">Login with Google</button>
    <pre id="user-info"></pre>
</body>
</html>

点击按钮你会进入平时你看到的google登陆的流程,流程成功后你会在前端页面看到用户的信息

就像这样

{"id":"13","email":"a1@gmail.com","verified_email":true,"name":"a ","given_name":"a","family_name":"a","picture":"https://lh3.googleusercontent.com/a/ACLXM=s96-c","locale":"zh-CN"}

同时后端也会在控制台打印出这个信息,我们已经成功通过了google的身份验证。我们可以再将他结合到自己的程序中