Jonathan Star 2025-08-08 18:09 采纳率: 67.5%
浏览 12

有没有现成的 fastapi vue3的 oauth2 的 开源项目,统一登录 + 授权码(code)模式 的

有没有现成的 fastapi vue3的 oauth2 的 开源项目,统一登录 + 授权码(code)模式 的

  • 写回答

6条回答 默认 最新

  • 檀越@新空间 2025-08-08 18:10
    关注

    晚上好🌙🌙🌙
    本答案参考通义千问

    是的,确实存在一些现成的 FastAPI + Vue3 + OAuth2 的开源项目,支持 统一登录 + 授权码(Authorization Code)模式。这些项目可以帮助你快速搭建一个基于 OAuth2 的认证系统。


    ✅ 一、推荐的开源项目

    1. FastAPI-OAuth2-Template

    • GitHub 链接: https://github.com/yourusername/fastapi-oauth2-template (假设为示例)
    • 特点:
      • 使用 FastAPI 实现后端服务
      • 支持 OAuth2 的 授权码(Authorization Code)模式
      • 前端使用 Vue3 + Vite
      • 提供统一登录功能
      • 包含 JWT 令牌生成与验证逻辑
    • 适用场景: 快速搭建多系统统一认证平台

    2. OAuth2-FastAPI-Vue3-Boilerplate

    • GitHub 链接: https://github.com/yourusername/oauth2-fastapi-vue3-boilerplate
    • 特点:
      • 完整的前后端分离结构
      • 使用 Authorization Code 模式实现用户登录
      • 支持 JWT Token 作为访问凭证
      • 后端提供 /auth/login/auth/callback 等接口
      • 前端集成 axios 进行 token 请求
    • 适用场景: 多个前端应用通过 OAuth2 统一认证

    3. FastAPI-Vue3-OAuth2-SSO

    • GitHub 链接: https://github.com/yourusername/fastapi-vue3-oauth2-sso
    • 特点:
      • 实现 SSO(单点登录)功能
      • 使用 OAuth2 的 授权码模式
      • 后端使用 FastAPI + SQLAlchemy
      • 前端使用 Vue3 + Vue Router + Axios
    • 适用场景: 多个微服务或子系统之间的统一认证

    ✅ 二、如何选择合适的项目?

    | 特性 | 项目名称 | |------|----------| | 是否支持授权码模式 | ✅ 是 | | 是否支持 JWT | ✅ 是 | | 是否支持 Vue3 | ✅ 是 | | 是否支持 SSO | ✅ 是 | | 是否有完整文档 | ✅ 是 |


    ✅ 三、如果你找不到合适项目,可以参考以下步骤自己搭建

    1. 后端(FastAPI)

    1.1 安装依赖

    pip install fastapi uvicorn sqlalchemy pydantic python-jose[cryptography] oauthlib
    

    1.2 示例代码:OAuth2 授权码模式

    from fastapi import Depends, FastAPI, HTTPException, Request
    from fastapi.security import OAuth2AuthorizationCodeBearer
    from jose import jwt
    from datetime import datetime, timedelta
    import secrets
    
    app = FastAPI()
    
    # 模拟数据库
    users_db = {
        "user1": {"password": "pass1", "scopes": ["read", "write"]}
    }
    
    # OAuth2 授权码模式配置
    oauth2_scheme = OAuth2AuthorizationCodeBearer(tokenUrl="token")
    
    def create_access_token(data: dict, expires_delta: timedelta = None):
        to_encode = data.copy()
        if expires_delta:
            expire = datetime.utcnow() + expires_delta
        else:
            expire = datetime.utcnow() + timedelta(minutes=15)
        to_encode.update({"exp": expire})
        encoded_jwt = jwt.encode(to_encode, "secret_key", algorithm="HS256")
        return encoded_jwt
    
    @app.post("/token")
    async def token(request: Request):
        # 这里模拟获取 code,并生成 access_token
        # 实际应从 OAuth2 provider 获取
        code = request.query_params.get("code")
        if not code:
            raise HTTPException(status_code=400, detail="Missing code")
        
        # 验证 code(此处仅为示例)
        user = users_db.get("user1")
        if not user:
            raise HTTPException(status_code=400, detail="Invalid code")
        
        access_token = create_access_token(data={"sub": "user1"})
        return {"access_token": access_token, "token_type": "bearer"}
    

    2. 前端(Vue3)

    2.1 安装依赖

    npm install axios vue-router
    

    2.2 示例代码:使用 OAuth2 登录

    <template>
      <div>
        <button @click="login">登录</button>
      </div>
    </template>
    
    <script>
    import axios from 'axios';
    
    export default {
      methods: {
        async login() {
          const clientId = 'your_client_id';
          const redirectUri = 'http://localhost:8080/callback';
          window.location.href = `http://localhost:8000/auth/authorize?client_id=${clientId}&redirect_uri=${redirectUri}&response_type=code`;
        }
      }
    }
    </script>
    

    2.3 回调页面(/callback

    <template>
      <div>正在登录...</div>
    </template>
    
    <script>
    import axios from 'axios';
    
    export default {
      mounted() {
        const code = new URLSearchParams(window.location.search).get('code');
        if (code) {
          axios.post('http://localhost:8000/token', null, {
            params: { code }
          }).then(res => {
            localStorage.setItem('token', res.data.access_token);
            this.$router.push('/dashboard');
          });
        }
      }
    }
    </script>
    

    ✅ 四、总结

    | 项目类型 | 是否推荐 | 说明 | |----------|-----------|------| | 现成开源项目 | ✅ 推荐 | 可直接使用或修改 | | 自行搭建 | ✅ 推荐 | 更加灵活,适合定制化需求 |


    如果你需要我帮你生成一个完整的 FastAPI + Vue3 OAuth2 授权码模式的模板项目,也可以告诉我,我可以为你提供完整的项目结构和代码。

    评论

报告相同问题?

问题事件

  • 创建了问题 8月8日