Git and Github SSH keys
Posted on 2020-05-17T00:45:41Z by Kevin Foong
This is part 2 of the Git and Github intro. See part 1 here.
If you are contributing to more than one Github account, for example one for work and one for home, you may need to set up SSH keys, one for each Github account to prevent permission denied error's and so that you don't have to keep re-entering your username and password. The below are instructions for Windows users on how you can do this.
- If you downloaded Git for Windows you will probably have “git bash” installed. Start git bash.
- Generate a ssh key
ssh-keygen -t rsa -C email@example.com
- It will ask “Enter file in which to save the key”. Save it to the below location. Ensure that you give the key some unique name (swap your values with the ones in UPPERCASE).
- It should generate 2 files in this location
- Open the .pub file using Notepad or any editor and copy everything in it. This is the SSH key and it should look something like this.
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCrEtsL8yG3g8Rf50s2n07znGxmegh9Z7QVMwWiflmnwNOEaOivS1OPWJAvCd6BqGjZ9HBWSSDxEbxv7GkDIkD+nCAujpSqxkw6Qw47INbVgSLu4jeJeUG5DN7we+7Vw/x2Qb+QLWQIoKIZSn+55UdEl4NjlncOmq5BUOoj5mS3e3oROzjFVwSyuFTRhBQ4zbCSUCvcx14UqcjNzz98E8UOWBdFjpYFeAkJl8BlAFWSQzJJKKllkmsx5Dn4erFI7H4eHLruKTkuhKll4zIfSIUYQdutjpq0PIqXwMi20PLVUGMX2VkKUXQAcT1iLh3J/HLgM+m3UMCtAa9q3QXN2iD firstname.lastname@example.org
- Go back to your project root location and find the .git folder. In the .git folder there should be a “config” file. Add the following lines into this files. Just swap your values with the ones in UPPERCASE.
sshCommand = ssh -i ~/.ssh/id_rsa_UNIQUENAME
url = email@example.com:GITHUB_USERNAME/GITHUB_REPONAME.git
- Back in your Github accout go to Settings > SSH and GPG keys and click New SSH key. Make sure the title you enter is descriptive and unique. Enter the key you created. It should look something like below
- Now do exactly the same for your second Github account. That is generate a new SSH key, add the key to Github and configure the project's ".git/config" file to use the key.
Now when you issue the comand “git push origin master” it should connect directly to Github without you needing to enter your username and password.
"Permission to .git denied to user" error
There is possibly one final step you need to do if you are still getting a "permission to .git denied to user" error when connecting to your second account for the first time. Git may still be using the credentials of your first account to connect to your second account. In this case just delete the Github credentials entry from Credential Manager. In Windows go to Credential Manager > Windows Credentials > Generic Credentials, delete the Github credentials and it should work.
This Stack Overflow thread provides more information about it.