How to Use curl with .netrc for Auto Authentication

This article explains how the curl command-line tool utilizes the .netrc file to automate user authentication. You will learn the purpose of the .netrc file, how to format it with your login credentials, and the specific curl flags required to securely auto-login to remote servers without exposing passwords in your terminal history.

What is a .netrc File?

The .netrc file is a plain text file stored in a user’s home directory (~/.netrc on Unix-like systems or _netrc on Windows). It contains login credentials for various remote machines. When configured correctly, curl can automatically parse this file to retrieve username and password details for a specific host, removing the need to input credentials manually or expose them in script files.

Structure of the .netrc File

The .netrc file uses a specific token-based format to map hosts to credentials. The basic structure consists of three main tokens: machine, login, and password.

Here is an example of how to format the file:

machine api.github.com
login your_username
password your_personal_access_token

machine ftp.example.com
login ftp_user
password secret_ftp_password

How to Trigger curl to Use .netrc

By default, curl ignores the .netrc file. To force curl to look up credentials in your .netrc file, you must use one of the following command-line flags:

1. The -n or --netrc Flag

This flag tells curl that it must scan the .netrc file for the host specified in the URL. If the host is found, curl automatically injects the corresponding credentials into the request.

curl -n https://api.github.com/user

If the host is not found in the .netrc file, curl will fall back to asking you for credentials via the terminal or fail the request.

2. The --netrc-optional Flag

This flag acts as a fallback. curl will attempt to use the .netrc file first. If the file does not exist, or if the specific host is not configured within the file, curl will proceed with the request without credentials (or use credentials provided by other command-line arguments like -u).

curl --netrc-optional https://api.github.com/user

3. The --netrc-file <path> Flag

If you want to keep your credentials in a file located somewhere other than your home directory, or if you want to use a different file name, you can specify the exact path to your credential file.

curl --netrc-file /path/to/custom_credentials.txt https://api.github.com/user

Security Requirements

Because the .netrc file contains plain text passwords, operating systems require strict file permissions.

On Linux and macOS, curl will refuse to read the .netrc file if its permissions are too public. You must restrict access to the file so that only your user account can read and write to it.

To set the correct permissions, run the following command in your terminal:

chmod 600 ~/.netrc

This ensures that other users on the same system cannot access your stored credentials.