githubsshssh-configmultiple-accounts

Permission to user1/repo denied to user2, can't push to two accounts without changing settings each time


I've seen some similar questions (in fact have tried the solution to every single one I've seen) but none have solved this. Essentially, I want to push to two different Github accounts without changing my config file every time.

I am trying to push to two different Github accounts from the same system, both with SSH. I am using WSL through VSCode. ssh -T works for both of my RSA files, both Github accounts have the corresponding SSH keys and I can push to each just fine, when my .ssh/config file has specific settings for each.

My .ssh/config file looks like this:

# Personal Account
Host github.com-user1
   HostName github.com
   User git
   IdentityFile ~/.ssh/id_rsa
    
# Work Account
Host github.com-user2
   HostName github.com
   User git
   IdentityFile ~/.ssh/id_rsa_user2

As is, pushing to account user1 works fine, but trying to push to account user2 gives error:

ERROR: Permission to user2/repo.git denied to user1.
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

HOWEVER, if I change the second stanza (#Work Account)'s first line to just Host github.com, I can suddenly push to account user2! I just... can't push to user1. I get the reverse of the above error, now Permission to user1/repo.git denied to user2.

I have tried:
Setting both as Host github.com, but this reverts me to my original problem (can push only as user1.)

It seems like it's just picking the first stanza in the .ssh/config file it sees (while prioritizing Host github.com), but I need it to be responsive to which account I'm pushing from.

git config user.name and user.email are set to the correct values for each repo. User2 uses local config & User1 uses the global config, but I don't think this is the problem since I've been able to push to both without adjusting this.

I've added PreferredAuthentications publickey and IdentitiesOnly yes to both stanzas, and some others I've seen in others' configurations of this file, but none have changed the error that gets output.

Control Panel > Manage Windows Credentials has no GitHub credentials associated with it (I checked, there weren't any, nothing has been altered/removed)


Solution

  • Once you've set up that stanza in your ~/.ssh/config, you then need to change each remote name to use either github.com-user1 or github.com-user2 as the host name in the SSH URL. That's the only way to get this to work reliably, and you can change the existing remote (e.g. origin) URL by running git remote set-url NEW-URL.

    Also note that you need the IdentitiesOnly yes option in each stanza as well.

    This is documented in the Git FAQ.