Permission denied using multiple Git user SSH keys

Viewed 756

Folks, it’s my first time to use multiple SSH keys for multiple users. I point out in the following all the steps I carried out:

Assume I have 2 GitHub users attached to 2 different GitHub accounts, user1 and user2 respectively.

1. I was able to generate different SSH keys for each user

2. Similarly, I have uploaded the respective private keys to each user account

3. Thereafter, I set up the SSH config file like this:

Host user1.github.com
    HostName github.com
    PreferredAuthentications publickey
    IdentityFile ~/.ssh/id_git_user1      # private key user1

Host user2.github.com
    HostName github.com
    PreferredAuthentications publickey
    IdentityFile ~/.ssh/id_git_ user2      # private key user2 

4. I cleared the SSH cache and load the new identities

ssh-add -D *
eval `ssh-agent -s`
ssh-add ~/.ssh/id_git_ user1
ssh-add ~/.ssh/id_git_ user2

and after issuing ssh-add -l, both keys are listed down

5. Whenever I create a new repo to any of them, I’m used to updating the local file .git/config.
For instance, I append the following config for each repo related to user1 manually:

[user]
    name = user1
    mail = user1@mail.com 

and I did the same for user2 repositories

The problem is, whenever I load both keys at step 4, I was unable to do git push using user1, and it throws this error.
Let’s assume repo_user1 is a newly created repository related to user1.

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

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

I doubt the problem is, git failed to load the right key of the current user cause when I redo step 4 and omit to load the second key, it works fine. The error also says denied to user2 though my config is set for user1.

I really appreciate any workaround to avoid repeating the same steps each time I push my update.

Thanks,

1 Answers

Try with the follwoign ~/.ssh/config file:

Host user1.github.com
    HostName github.com
    PreferredAuthentications publickey
    IdentityFile ~/.ssh/id_git_user1      # private key user1
    User git

Host user2.github.com
    HostName github.com
    PreferredAuthentications publickey
    IdentityFile ~/.ssh/id_git_ user2      # private key user2 
    User git

Then, for repo1, make sure to use the right SSH URL:

cd /path/to/repo1
git remote set-url user1.github.com:user1/repo_user1.git

That will use ~/.ssh/id_git_user1.

Related