Enforce SSH instead of HTTP for Git Operations

Enforce SSH instead of HTTP for Git Operations

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!


Generate the SSH keys

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

sh

ssh-keygen

Choose a key name that is easy for you to remember, example personal-github or work-bitbucket, …


Add the public key to your git account

Copy the contents of your .pub key and add it to your git account, it is usually under SettingsSSH


Enforce your system to use SSH instead of Http

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.

In your ~/.gitconfig file:

text

# Enforce SSH instead of Http for git websites ## Github [url "ssh://git@github.com/"] insteadOf = https://github.com/ ## Gitlab [url "ssh://git@gitlab.com/"] insteadOf = https://gitlab.com/ ## Bitbucket [url "ssh://git@bitbucket.org/"] insteadOf = https://bitbucket.org/

Tell your system which key to use for each git website

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.

In your ~/.ssh/config file:

text

# 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 clone, fetch, pull, …

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 👋