如何集成GitHub登录:四步指南

问题

还记得用户需要为每个应用设置唯一的用户名和密码的日子吗?现在是时候向前迈进了。

通过集成 GitHub Sign-In,让我们可以更简单地登录您的应用程序,这对开发人员和技术娴熟的用户来说是一个不错的选择。

解决方案

GitHub OAuth 允许您无缝地验证用户并通过 GitHub 的 API 访问他们的公开个人资料或其他数据。

让我们将其分解为前端和后端可管理的步骤。

步骤 1:在 GitHub 上注册你的应用

  • 转到 GitHub 设置:导航到 GitHub 开发人员设置。
  • OAuth 应用程序:单击侧栏中的 OAuth 应用程序。
  • Image description
  • 注册新的 OAuth 应用:主页 URL:使用 http://localhost:3000(或您应用的本地 URL)。授权回调 URL:使用 http://localhost:3000(或您计划集成 GitHub Sign-In 的部署 URL)。您可以稍后更新这些内容。
  • Image description
  • 复制客户端 ID:创建后,GitHub 将提供客户端 ID。
  • 创建客户端密钥:生成后端操作所需的客户端密钥,例如用令牌交换用户数据。
  • Image description

    第 2 步:前端实现

    添加 GitHub 登录按钮

    使用以下 HTML 和 CSS 显示 GitHub 登录按钮:

    .github-signin-container {
      background-color: #000;
      transition: background-color 0.3s ease;
      border-radius: 6px;
      border: none;
    }
    
    .github-signin-btn {
      display: flex;
      align-items: center;
      justify-content: center;
      background-color: #000;
      color: #fff;
      font-size: 16px;
      font-weight: 600;
      padding: 10px 20px;
      border: none;
      border-radius: 6px;
      cursor: pointer;
      text-decoration: none;
      transition: background-color 0.3s ease;
      width: 100%;
    }
    
    .github-signin-btn:hover {
      background-color: #333;
    }
    
    .github-signin-btn .github-icon {
      width: 25px;
      height: 25px;
      margin-right: 8px;
    }
    
    .github-signin-btn span {
      font-family: Arial, sans-serif;
      font-size: 16px;
    }

    处理登录按钮点击

    使用 JavaScript 将用户重定向到 GitHub 的授权页面:

    const handleGithubLogin = () => {
      const githubAuthUrl = `https://github.com/login/oauth/authorize?client_id=${GITHUB_CLIENT_ID}&redirect_uri=${REDIRECT_URI}&scope=read:user`;
      window.location.href = githubAuthUrl;
    };

    用您的值替换“GITHUB_CLIENT_ID”和“REDIRECT_URI”。

    步骤 3:处理 GitHub 的重定向

    GitHub 将使用 `?code= 重定向回你的应用程序`。使用此代码来交换访问令牌。

    useEffect(() => {
      const params = new URLSearchParams(window.location.search);
      const code = params.get("code");
    
      if (!code) return;
    
      const target = `https://backend.com/external-signup?app=${appName}&accessToken=${code}&provider=github`;
      callBackendAPI("GET", target);
    }, []);

    这会将代码发送到您的后端,以便安全地将其交换为访问令牌。

    步骤 4:后端实现

    使用授权码交换访问令牌

    使用 GitHub 的 OAuth 令牌端点:

    const GITHUB_ACCESS_TOKEN_URL = 'https://github.com/login/oauth/access_token';
    
    const url = `${GITHUB_ACCESS_TOKEN_URL}?client_id=${GITHUB_CLIENT_ID}&client_secret=${GITHUB_SECRET_ID}&code=${request.body.code}`;
    
    const response = await fetch(url, {
      method: "GET",
      headers: {
        Accept: "application/json",
        "Accept-Encoding": "application/json",
      },
    });
    
    const githubUserData = await response.json();
    const accessToken = githubUserData.access_token;

    将“GITHUB_CLIENT_ID”和“GITHUB_SECRET_ID”替换为步骤 1 中的值。

    获取用户数据

    使用访问令牌,调用 GitHub 的用户 API 来检索用户信息:

    const GITHUB_USER_API_URL = "https://api.github.com/user";
    
    const userProfileResponse = await fetch(GITHUB_USER_API_URL, {
      method: "GET",
      headers: {
        Accept: "application/vnd.github+json",
        Authorization: `Bearer ${accessToken}`,
        "X-GitHub-Api-Version": "2022-11-28",
      },
    });
    
    const userProfileData = await userProfileResponse.json();
    
    const email = userProfileData.email;
    const name = userProfileData.name;
    const picture = userProfileData.avatar_url;
    Image description

    使用此数据在数据库中创建或更新用户。

    总结

  • 在 GitHub 上注册您的应用以获取客户端 ID 和客户端密钥。
  • 在您的前端添加一个 GitHub 登录按钮。
  • 将用户重定向到 GitHub 的 OAuth 页面进行登录。
  • 使用授权码处理重定向。
  • 在后端用代码交换访问令牌。
  • 使用令牌从 GitHub 的 API 获取用户数据。
  • 福利:LiveAPI 让你的生活更轻松

    我正在开发一款名为 LiveAPI 的工具,它可以直接从您的代码库生成安全、美观的 API 文档。额外好处:它允许您执行 API 并以任何语言生成请求片段!

    LiveAPI

    尝试一下,节省文档时间,同时专注于您的应用程序。祝您编码愉快!