How to Provide Basic Auth Credentials in Curl
Sending Basic Authentication credentials with curl is a fundamental
task for interacting with protected APIs and web servers. This article
provides a quick, direct guide on how to pass usernames and passwords
using curl’s built-in options, including the -u flag,
prompting for passwords securely, and passing manual Authorization
headers.
Method 1: Using the -u or –user Flag
The most common and straightforward way to provide Basic
Authentication credentials in curl is by using the -u (or
--user) option.
To send both the username and password in a single command, use the following syntax:
curl -u username:password https://api.example.com/dataPrompting for the Password Safely
Specifying the password directly in the command line leaves it visible in your terminal history. To avoid this security risk, you can provide only the username. Curl will safely prompt you to type the password without echoing it on the screen:
curl -u username https://api.example.com/dataMethod 2: Manually Sending the Authorization Header
Basic Authentication works by sending a Base64-encoded string of the
username:password pair inside the HTTP
Authorization header. If you prefer to construct this
header manually, you can use the -H (or
--header) option.
First, encode your credentials to Base64. For example, in Linux or macOS:
echo -n "username:password" | base64If the output is dXNlcm5hbWU6cGFzc3dvcmQ=, you can pass
it in the curl command like this:
curl -H "Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=" https://api.example.com/dataHandling Special Characters in Passwords
If your password contains special characters (such as !,
@, #, or $), your terminal shell
might misinterpret them. To prevent errors, wrap the credentials in
single quotes:
curl -u 'username:p@$$word!' https://api.example.com/data