Perform Basic Authentication using cURL with Examples


There are two ways in which you can perform basic auth using cURL,

  1. Using the -u or --user option
  2. Using the Authorization header in the request

Using the -u or --user option

In other to perform Basic Authentication using cURL command make use of -u or the --user option followed by user:password along with the cURL command request.

Syntax:

curl -u <user-name:password> the-url

Example:
% curl -u newuser:mypassword https://example.org

Note: If your username or password contains special characters, make sure the wrap the 'user:password' within single quotes.

Example: Basic Auth cURL with special character is user or password
% curl -u 'new_user:my$password' https://example.org

Note: As the colon is used as a separator to distinguish the username and password, you cannot have a colon as a character in the username, but you can have it in the password string.


If you do not provide the password with the -u option and just provide the user, cURL will prompt you to enter the password.

Example: cURL Basic Auth with password prompt
% curl -u newuser https://example.org 
Enter host password for user 'newuser':
cURL Request using Basic Auth with -u option


Perform Basic Auth by passing Authorization Header in cURL Request

The username:password string needs to be Base64-Encoded and passed in as a Header to your cURL request as below,

Plan text user:password
myuser:my$password
Base64 Encoded user:password
bXl1c2VyOm15JHBhc3N3b3Jk


cURL Example using Authorization Header
curl 'https://example.org' \
--header 'Authorization: Basic bXl1c2VyOm15JHBhc3N3b3Jk
cURL Basic Auth using Authorization Header

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org



















Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap