Security

Git 凭据助手配置

配置 Git credential helper,避免频繁输入用户名密码,同时确保凭据存储安全。

适合谁看
  • 需要配置 Git 安全认证的开发者
前置知识
  • 知道 SSH 的基本概念
  • 有命令行操作经验
常见风险
  • 密钥管理不当导致安全泄露
  • 不理解签名策略导致提效验证失败

概述

每次 Git 操作都输入用户名和密码效率很低。credential helper 可以安全地缓存或存储凭据,自动提供给 Git 操作。

常用凭据助手

Helper存储方式适用场景
cache内存缓存(可设置过期时间)短期使用,安全
osxkeychainmacOS 钥匙串macOS 用户
manager-coreWindows Credential ManagerWindows 用户
libsecretLinux Secret ServiceLinux 桌面用户
store明文磁盘文件⚠️ 不推荐

配置方法

macOS: osxkeychain

# 通常 git-credential-osxkeychain 已随 Git 安装
git config --global credential.helper osxkeychain

# 验证
git config --global --get credential.helper
# 输出: osxkeychain

第一次操作时会弹出钥匙串访问确认,同意后后续无需再次输入。

内存缓存

# 默认缓存 15 分钟
git config --global credential.helper cache

# 自定义缓存时间(单位:秒)
git config --global credential.helper "cache --timeout=3600"
# 缓存 1 小时

适合短期使用,重启后缓存清空。

Linux: libsecret

# 安装 libsecret
sudo apt-get install libsecret-1-0 libsecret-1-dev
sudo make --directory=/usr/share/doc/git/contrib/credential/libsecret

# 配置
git config --global credential.helper /usr/share/doc/git/contrib/credential/libsecret/git-credential-libsecret

多 Host 配置

可以为不同的 Git 托管平台使用不同的凭据助手:

# 全局使用 osxkeychain
git config --global credential.helper osxkeychain

# 对特定 host 使用 cache
git config --global credential.https://gitlab.com.helper cache

凭据上下文

Git 根据 URL 匹配凭据上下文。常见配置:

# ~/.gitconfig
[credential]
  helper = osxkeychain

[credential "https://github.com"]
  username = your-github-username

[credential "https://gitlab.com"]
  username = your-gitlab-username

安全建议

  1. 不要使用 store helper:它以明文存储凭据,任何能访问磁盘的人都能读取
  2. HTTPS vs SSH:SSH 密钥通常比 HTTPS 凭据更适合长期使用
  3. 定期清理:定期检查存储的凭据,移除不再使用的
  4. 环境隔离:工作与个人仓库使用不同的凭据配置

常见问题

凭据助手不工作

# 调试:查看 Git 尝试使用的 helper
GIT_TRACE=1 git fetch

# 强制指定 helper
git -c credential.helper=osxkeychain fetch

清除缓存的凭据

# 清除所有凭据缓存
git credential-cache exit

# 或手动删除钥匙串中的条目(macOS)
open /Applications/Utilities/Keychain\ Access.app

继续学习

  1. security/ssh-key-management — SSH 密钥管理
  2. security/signing-advanced — 提交签名进阶
  3. security/gpg-signing — GPG 签名基础