Skip to content

Authentication using a .netrc file

There's many different ways to setup authentication on GIT: SSH keys and personal access tokens when setting up a git remote are pretty straightforward, but my preferred one is using a .netrc file. It works pretty much the same whether you're setting up your local workstation or a CICD pipeline somewhere like Jenkins or AzureDevOps and it also works for fetching Golang dependencies which rely on git (when using go get).

The concept

The first time I stumbled upon .netrc was in this documentation by IBM. It consists of a specific file (yes, .netrc) which resides in the $HOME directory of a Unix system and allows the computer to authenticate to different machine hosts for a variety of services (e.g.: git, ftp, etc.).

Added bonus!

You can setup access to multiple hosts using different accounts.

on Unix

  1. Open a terminal.
  2. Navigate to your $HOME folder by $ cd $HOME or $ cd ~
  3. Create a .netrc file there with the following contents (one line per host).
    machine mvs1.tcp.raleigh.ibm.com login tonystark password ironman
    machine 9.67.112.25 login tonystark password foobar
    machine github.com login <yourId> password <yourPersonalAccessToken>
    machine github.acme.com login <yourId> password <yourPersonalAccessToken>
    
  4. DONE! Now the terminal is "aware" of which credentials to use where for different network services.

As you can see a host can be a DNS name entry, IPv4 or IPv6 address. One special thing about GitHub is that you should set it up using a token instead of you regular GitHub account password.

Where do I get a GitHub token?

GitHub shows you the steps on this documentation.

Warning

Treat your access tokens like passwords. Don't ever commit them to source control or share them. If that happens rotate them immediatelly. Also consider using more selective token scopes instead of granting tokens access to everything. GitHub allows you to do that via OAuth scopes.

on Windows

Oh, so you're running Windows? Fear not, we've got you covered!

As windows has different environment variables, we need to have it point what it considers a user's HOME folder, here's how you can create .netrc:

  1. Open a command prompt or PowerShell terminal.
  2. setup HOME to point to Windows' version of it by running setx HOME %USERPROFILE%.
  3. run echo %HOME% and verify it points to the current user's HOME folder (e.g.: C:\Users\YOURNAME).
  4. Create a _netrc instead of a .netrc file same as on step #3 for unix.

Done

Now you can git clone https://... instead of using ssh (as it's common practice in companies to disable SSH services), go get Golang libraries that are behind a GIT server that requires authentication and save the planet among other things.

hack