Skip to content

在 Visual Studio Code 中配置 GitHub 个人访问令牌

问题概述

GitHub 自 2021 年 8 月起要求使用基于令牌的认证方式替代传统密码认证。许多 Visual Studio Code 用户在推送到 GitHub 仓库时会遇到认证失败的问题。本文将详细介绍如何在 VS Code 中正确配置个人访问令牌(PAT)以确保正常的 Git 操作。

注意

传统的用户名密码认证已不再适用于 GitHub 操作,必须使用个人访问令牌或 SSH 密钥进行认证。

解决方案

方法一:使用 Git 远程 URL 设置令牌(推荐)

这是最直接且可靠的方法,适用于所有操作系统:

  1. 生成个人访问令牌

    • 访问 GitHub Token 设置页面
    • 点击 "Generate new token"
    • 选择适当权限(至少需要 repo 权限)
    • 复制生成的令牌(如 ghp_xxxxxxxxxxxx
  2. 更新远程仓库 URL

    bash
    git remote set-url origin https://<TOKEN>@github.com/<USERNAME>/<REPO>.git

    示例:

    bash
    git remote set-url origin https://ghp_a7b1992958fe65d1c@github.com/sampleuser/sampleproject.git
  3. 验证配置

    bash
    git remote -v

    输出应显示包含令牌的 URL。

提示

确保令牌中包含必要的 workflow 权限,如果你使用 GitHub Actions。

方法二:使用 Git 凭证管理器

对于希望自动管理凭证的用户:

  1. 清除旧凭证

    bash
    printf "protocol=https\nhost=github.com\nusername=<USERNAME>" | git credential-manager-core erase
  2. 存储新令牌

    bash
    printf "protocol=https\nhost=github.com\nusername=<USERNAME>\npassword=<TOKEN>" | git credential-manager-core store
安装 Git Credential Manager Core

如果遇到 git: 'credential-manager-core' is not a git command 错误,需要先安装 GCM Core

方法三:通过 VS Code 界面配置

  1. 尝试执行 Git 操作(推送或拉取)
  2. 点击底部状态栏的 "Signing into GitHub" 提示
  3. 在浏览器中完成授权流程
  4. 返回 VS Code 并粘贴令牌

注意

某些情况下可能需要尝试两次操作才会出现认证提示。

故障排除

macOS 密钥链问题

如果凭证被缓存:

  1. 打开钥匙串访问应用
  2. 搜索并删除 github.comvscode.github.com 相关条目
  3. 重新尝试 Git 操作

验证当前配置

使用以下命令检查当前远程配置:

bash
git config --local -e

确认 [remote "origin"] 部分包含正确的 URL。

最佳实践

  1. 令牌安全:不要将令牌硬编码在脚本或配置文件中
  2. 权限最小化:只为令牌授予必要的权限
  3. 定期更新:定期轮换令牌以提高安全性
  4. 使用 SSH 替代:考虑使用 SSH 密钥进行认证,更为安全方便

结论

配置 GitHub 个人访问令牌后,Visual Studio Code 将能够正常进行 Git 操作。推荐使用方法一直接设置远程 URL,这是最可靠且跨平台的解决方案。如果遇到问题,检查凭证管理器的配置或清除缓存的凭证通常能解决问题。