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¶
- Open a terminal.
- Navigate to your
$HOMEfolder by$ cd $HOMEor$ cd ~ - Create a
.netrcfile there with the following contents (one line per host). - 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:
- Open a command prompt or PowerShell terminal.
- setup
HOMEto point to Windows' version of it by runningsetx HOME %USERPROFILE%. - run
echo %HOME%and verify it points to the current user'sHOMEfolder (e.g.:C:\Users\YOURNAME). - Create a
_netrcinstead of a.netrcfile 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.
