When you use HTTPS, you need to authenticate (supply a username and password) each time you take an action that communicates with the remote server. Let’s see how we can use SSH (secure shell) to communicate with git websites like Github or Bitbucket and avoid having to manually type a password.
However, when using SSH, you create a key pair that contains a private key (saved to your local computer) and a public key (uploaded to your git website). The website then uses the key pair to authenticate anything the associated account can access. This two-way mechanism makes performing git operations on your computer easier and prevents man-in-the-middle attacks.
In this quick tutorial, we will see how to generate keys, add them to your git website, and enforce the system to use SSH for all git operations. Let’s start!
First things first, we need to generate a new SSH key.
Move to your
~/.ssh directory —create a new folder if you don’t have it already—, and use the following command to create a new ssh key pair
Choose a key name that is easy for you to remember, example
Copy the contents of your .pub key and add it to your git account, it is usually under Settings → SSH
Now that the key is added to your git account, we need to tell the system to use SSH instead of HTTPS for all requests to that website.
# Enforce SSH instead of Http for git websites ## Github [url "ssh://firstname.lastname@example.org/"] insteadOf = https://github.com/ ## Gitlab [url "ssh://email@example.com/"] insteadOf = https://gitlab.com/ ## Bitbucket [url "ssh://firstname.lastname@example.org/"] insteadOf = https://bitbucket.org/
In the previous step, we enforced the system to replace any HTTPS request with SSH for the git website, however, we need to specify which key to use as well, otherwise, git requests will fail.
# Specify SSH key for each Git website ## Github Host github.com User git IdentityFile ~/.ssh/<YOUR_SSH_KEY_NAME> ## Gitlab Host gitlab.com User git IdentityFile ~/.ssh/<YOUR_SSH_KEY_NAME> ## Bitbucket Host bitbucket.org User git IdentityFile ~/.ssh/<YOUR_SSH_KEY_NAME>
With the above setup, the system will use SSH automatically when performing git operations like
Note that this will work for git operations other packages perform like Cocoapods!
That’s it for now. If you have any questions, suggestions, or feedback, please let me know via Twitter 👋