-1

On my device, I have multiple repositories that can be accessed by different accounts.

Is there a way wherein I can use a specific SSH key for authentication depending on the GitHub repository?

Dominic Orga
  • 457
  • 6
  • 12

1 Answers1

3

Say you want to clone Repository A and Repository B, but they can only be accessed by User A and User B respectively.

Assuming that you have successfully created an SSH key for each user, you can create a SSH configuration file saved at ~/.ssh/config with the following content:

Host user-a
    HostName github.com
    IdentityFile ~/.ssh/id_rsa_user_a

Host user-b
    HostName github.com
    IdentityFile ~/.ssh/id_rsa_user_b

Afterwards, clone the repositories by replacing the github.com portion of the git SSH repo URL with the preferred host like so:

# Replace git@github.com:test/repo_A.git
git clone git@user-a:test/repo_A.git

# Replace git@github.com:test/repo_B.git
git clone git@user-b:test/repo_B.git

If you already have an existing repository on your device and you wanted to use a different account (a.k.a different SSH key) for pushing changes, you can create a new remote as follows:

# Create new remote for user B
git remote add origin_user_b git@user-b:test/existing_repo.git

# Push changes with user B
git push origin_user_b

NOTE: This will not change the author of the commit. To do this, you can refer to this other Stackoverflow answer instead.

Dominic Orga
  • 457
  • 6
  • 12