gitgithubgistgit-credential-manager

Using multiple git personal access tokens (PAT) with Credential Manager


I'm using GitCredentialManager as per this answer but I can't find a way on how to use multiple Personal Access Tokens (PAT).

I have

  1. a Windows terminal gist at https://gist.github.com/lkeersmaekers/4884d047b3b90ccd697a4d7ec21be49d
  2. a dotvim repo at https://github.com/lkeersmaekers/dotvim

I created

  1. a PAT for the Windows terminal gist (Create gists scope)
  2. a PAT for the dotvim repo (Access public repositories scope)

When pushing the Windows terminal the gist a first time, git asks for a username/password(=PAT) as expected, the push succeeds and I can see the credential in Windows Credential Manager.

When pushing the dotvim repo thereafter however uses that stored credential (PAT) from Windows terminal and the dotvim push fails.

I'm unsure at what is the best practice here.


Solution

  • There are a couple different approaches you can take here. One is to create a single token with the gist and repo scopes and use that generally. That token does have access to all your repositories, but if you're using a credential helper, then it's stored in an encrypted way and it shouldn't be too risky.

    Since you're actually using two different domains here (github.com and gist.github.com), you can use separate tokens without a problem. Tokens are stored scoped on the domain, so there's no conflict here. Just use each credential on its respective domain.

    If you want to use different tokens for different repositories, you can do that by setting credential.usehttppath to true. That can also be scoped to a particular URL pattern (including wildcards) such that you it only applies to GitHub (e.g., with git config --global credential.https://github.com/.usehttppath true). Each repository will then have its own set of credentials, and you can store as many tokens as you like. If you have a lot of repositories, this will likely become inconvenient quickly, though.

    Finally, if you just want to have different tokens for public and private access, you can do this for GitHub by taking advantage of the fact that GitHub ignores the username when you use a token. You can therefore clone public repositories by putting a public@ before the hostname (e.g., https://public@github.com/git/git.git) and then using private@ for private repositories. Git's credential helpers will store separate credentials for these fake usernames and the respective token will be used.