How do I use different PATs for different git-service endpoints?

Viewed 45

I use both GitLab and GitHub(s) for different kinds of work. They all have their different Personal Access Tokens (PATs) that are displayed once at creation. Currently I put them in a password manager and copy/paste per repo or action. A frustrating, time-consuming, and mistake prone process.

Is there a way to configure git to use different credentials based on HTTPS endpoint? When I go to gitlab.com - whether cloning, pushing, creating, whatever - it uses one set of credentials, and when going to github.com it uses another?

I'm using the command line in MacOs & Windows WSL - both with zsh if that is important.

1 Answers

If you're using the Git Credential Manager you can have it store the credentials on a per path basis. GCM can be used on with MacOS's keychain and the Windows Credentials Manager without additional configuration. For Linux the configuration depends on your distro/tool chain. GCM ships with recent versions of Git for Windows at least. For Mac and Linux I'm not sure about that, so you may need to install it separately.

You do need to add some extra config to your git config for that to work in case you access repos on a single host with multiple credentials.

git config --global credential.https://hostname.of.your.git.net/with/optional/root/path.useHttpPath true

That way GCM knows to store the credentials on a per path basis instead of at the host level. That way it prompts per path you configure and will store the credintials.

You can also explicitly parr in a different user to your origin url. GCM will use this to store a different token:

# new repo
git clone https://user@yourhost.net/path

#existing repo
git remote set-url origin https://contrib123@example.com/open-source/library.git

More details in the GCM docs on supporting multiple identities

You can also configure your git in WSL to use the GCM installed in windows to store the access keys in one central place.

If you also want to store a different name and email, then one trick you can employ is, to put all your work repos in one folder and all your private repos in another locally. Then in the root of that folder, you can create another .gitconfig and put the name and email configs in there. Git will traverse the path to look for configuration information prior to looking at the global git config.

Related