You want to do this so you don’t have to authenticate yourself interactively with your Git hosting service (GitHub/Gitlab/Bitbucket..) over and over again.

Solution: use SSH keys

When working with a remote git repository, you’ll often need to identify yourself to the repository using your credentials (username and password).

An SSH key is an alternate way to identify yourself that doesn’t require you to enter you username and password every time.

What are SSH keys?

SSH keys provide a more secure way of logging into a server than using a password alone.

While a password can eventually be cracked with a brute force attack, SSH keys are nearly impossible to decipher by brute force alone.

Generating a key pair provides you with two long strings of characters: a public and a private key.

You can place the public key on any server (like GitHub), and then unlock it by connecting to it with a client that already has the private key (your computer).

When the two match up, the system unlocks without the need for a password.

  • you can increase security even more by protecting the private key with a passphrase

How to setup SSH keys with your Git repository hosting service

If you plan to push/pull/etc using SSH, you need to set up SSH keys.

Below are the links for instructions on how to set up SSH keys for the most popular Git hosting services:

Enforce your system to use SSH instead of Http

Now that the public SSH key is added to your git account, you need to tell your computer to use SSH instead of HTTPS for all requests to your Git hosting service.

Modify your ~/.gitconfig file like this:

# 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/

Alternatively, if you don’t want to edit this file by hand, you can give the following commands:

$ git config --global --add url."git@github.com:".insteadOf "https://github.com/"
$ git config --global --add url."git@gitlab.com:".insteadOf "https://gitlab.com/"
$ git config --global --add url."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 hosting service, however, we need to specify which key to use as well, otherwise, git requests will fail.

In your ~/.ssh/config file:

# 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 all this setup, your computer will use SSH automatically when performing git operations like clone, fetch, pull, etc…