Velvet Star Monitor

Standout celebrity highlights with iconic style.

updates

Using cURL with a username and password?

Writer Mia Lopez

I want to access a URL which requires a username/password. I'd like to try accessing it with curl. Right now I'm doing something like:

curl 

I get an error. I guess I need to specify a username and password along with the above command.

How can I do that?

20 Answers

Use the -u flag to include a username, and curl will prompt for a password:

curl -u username 

You can also include the password in the command, but then your password will be visible in bash history:

curl -u username:password 
17

It is safer to do:

curl --netrc-file my-password-file 

...as passing a plain user/password string on the command line, is a bad idea.

The format of the password file is (as per man curl):

machine <example.com> login <username> password <password>

Note:

  1. Machine name must not include https:// or similar! Just the hostname.
  2. The words 'machine', 'login', and 'password' are just keywords; the actual information is the stuff after those keywords.
11

Or the same thing but different syntax

curl 
8

You can also just send the user name by writing:

curl -u USERNAME 

Curl will then ask you for the password, and the password will not be visible on the screen (or if you need to copy/paste the command).

To securely pass the password in a script (i.e. prevent it from showing up with ps auxf or logs) you can do it with the -K- flag (read config from stdin) and a heredoc:

curl --url url -K- <<< "--user user:password"
4

Usually CURL command refer to as

curl -u USERNAME:PASSWORD

if you don't have any password or want to skip command prompt to demand for password simple leave the password section blank.

i.e. curl -u USERNAME:

1
curl -X GET -u username:password {{ }} -O
1

pretty easy, do the below:

curl -X GET/POST/PUT <URL> -u username:password
2

Other answers have suggested netrc to specify username and password, based on what I've read, I agree. Here are some syntax details:

Like other answers, I would like to stress the need to pay attention to security regarding this question.

Although I am not an expert, I found these links insightful:

To summarize:

Using the encrypted versions of the protocols (HTTPS vs HTTP) (FTPS vs FTP) can help avoid Network Leakage.

Using netrc can help avoid Command Line Leakage.

To go a step further, it seems you can also encrypt the netrc files using gpg

With this your credentials are not "at rest" (stored) as plain text.

1

To let the password least not pop up in your .bash_history:

curl -u user:$(cat .password-file) 
2

I had the same need in bash (Ubuntu 16.04 LTS) and the commands provided in the answers failed to work in my case. I had to use:

curl -X POST -F 'username="$USER"' -F 'password="$PASS"' ""

Double quotes in the -F arguments are only needed if you're using variables, thus from the command line ... -F 'username=myuser' ... will be fine.

Relevant Security Notice: as Mr. Mark Ribau points in comments this command shows the password ($PASS variable, expanded) in the processlist!

3

You can use command like,

curl -u user-name -p > new-file-name.ext

Then HTTP password will be triggered.

Reference:

2

Plain and simply put the most secure way would be to use environment variables to store/retrieve your credentials. Thus a curl command like:

curl -Lk -XGET -u "${API_USER}:${API_HASH}" -b cookies.txt -c cookies.txt -- ""

Would then call your restful api and pass the http WWW_Authentication header with the Base64 encoded values of API_USER and API_HASH. The -Lk just tells curl to follow http 30x redirects and to use insecure tls handling (ie ignore ssl errors). While the double -- is just bash syntax sugar to stop processing command line flags. Furthermore, the -b cookies.txt and -c cookies.txt flags handle cookies with -b sending cookies and -c storing cookies locally.

The manual has more examples of authentication methods.

2

The safest way to pass credentials to curl is to be prompted to insert them. This is what happens when passing the username as suggested earlier (-u USERNAME).

But what if you can't pass the username that way? For instance the username might need to be part of the url and only the password be part of a json payload.

tl;dr: This is how to use curl safely in this case:

read -p "Username: " U; read -sp "Password: " P; curl --request POST -d "{\"password\":\"${P}\"}" unset P U

read will prompt for both username and password from the command line, and store the submitted values in two variables that can be references in subsequent commands and finally unset.

I'm gonna elaborate on why the other solutions are not ideal.

Why are environment variables unsafe

  1. Access and exposure mode of the content of an environment variable, can not be tracked (ps -eww ) since the environment is implicitly available to a process
  2. Often apps grab the whole environment and log it for debugging or monitoring purposes (sometimes on log files plaintext on disk, especially after an app crashes)
  3. Environment variables are passed down to child processes (therefore breaking the principle of least privilege)
  4. Maintaining them is an issue: new engineers don't know they are there, and are not aware of requirements around them - e.g., not to pass them to sub-processes - since they're not enforced or documented.

Why is it unsafe to type it into a command on the command line directlyBecause your secret then ends up being visible by any other user running ps -aux since that lists commands submitted for each currently running process. Also because your secrte then ends up in the bash history (once the shell terminates).

Why is it unsafe to include it in a local fileStrict POSIX access restriction on the file can mitigate the risk in this scenario. However, it is still a file on your file system, unencrypted at rest.

2

In some API maybe it does not work (like rabbitmq).

there is alternative:

curl
curl 

also the above format is usable in browsers.

You can use gpg encrypted netrc file with curl like so:

netrc_file="$HOME/netrc.gpg"
curl --netrc-file <(gpg -d $netrc_file) 

This is MUCH more than the OP asked for, but since this is a top result for securely passing passwords to curl, I'm adding these solutions here for others who arrive here searching for that.


NOTE: -s arg for read command is not POSIX, and so is not available everywhere, so it won't be used below. We will use stty -echo and stty echo instead.

NOTE: All bash variables below could instead be declared as locals if in a function, rather than unsetting.

NOTE: perl is pretty generally available on all systems I've tried due to it being a dependency for many things, whereas ruby and python are not, so using perl here. If you can guarantee ruby/python where you're doing this, you can replace the perl command with their equivalent.

NOTE: Tested in bash 3.2.57 on macOS 10.14.4. Some small translation may be required for other shells/installs.


Securely prompt a user for a (reusable) password to pass to curl. Particularly useful if you need to call curl multiple times.

For modern shells, where echo is a built-in (check via which echo):

url='
printf "Username: "
read username
printf "Password: "
stty -echo # disables echoing user input, POSIX equivalent for 'read -s'
read pass
printf "\n" # we need to move the line ahead
stty echo # re-enable echoing user input
echo ${pass} | sed -e "s/^/-u ${username}:/" | curl --url "${url}" -K-
unset username
unset pass

For older shells, where echo is something like /bin/echo (where whatever it echos can be seen in the process list):
THIS VERSION CANNOT REUSE THE PASSWORD, see lower down instead.

url='
printf "Username: "
read username
printf "Password: "
stty -echo # disables echoing user input, POSIX equivalent for 'read -s'
perl -e ' my $val=<STDIN>; chomp $val; print STDERR "\n"; # we need to move the line ahead, but not send a newline down the pipe print $val;
' | sed -e "s/^/-u ${username}:/" | curl --url "${url}" -K-
stty echo # re-enable echoing user input
unset username



If you happen to need to store the password temporarily to a file, to re-use it for multiple commands before clearing it (say because you're using functions for code re-use and don't want to repeat code and can't pass the value around via echo). (Yes, these are a little contrived looking in this form not being functions in different libraries; I tried to reduce them to the minimum code needed to show it.)

When echo is built-in (this is especially contrived, since echo is a built-in, but provided for completeness):

url='
filepath="$(mktemp)" # random path, only readable by current user
printf "Username: "
read username
printf "Password: "
stty -echo # disables echoing user input, POSIX equivalent for 'read -s'
read pass
echo "${pass}" > "${filepath}"
unset pass
printf "\n" # we need to move the line ahead
stty echo # re-enable echoing user input
cat "${filepath}" | sed -e "s/^/-u ${username}:/" | curl --url "${url}" -K-
rm "${filepath}" # don't forget to delete the file when done!!
unset username

When echo is something like /bin/echo:

url='
filepath="$(mktemp)" # random path, only readable by current user
printf "Username: "
read username
printf "Password: "
stty -echo # disables echoing user input, POSIX equivalent for 'read -s'
$(perl -e ' my $val=<STDIN>; chomp $val; open(my $fh, ">", $ARGV[0]) or die "Could not open file \"$ARGV[0]\" $\!"; print $fh $val; close $fh;
' "$filepath")
printf "\n" # we need to move the line ahead
stty echo # re-enable echoing user input
cat "${filepath}" | sed -e "s/^/-u ${username}:/" | curl --url "${url}" -K-
rm "${filepath}" # don't forget to delete the file when done!!
unset username

If you are on a system that has Gnome keyring app a solution that avoids exposing the password directly is to use gkeyring.py to extract the password from the keyring:

server=server.example.com
file=path/to/my/file
user=my_user_name
pass=$(gkeyring.py -k login -tnetwork -p user=$user,server=$server -1)
curl -u $user:$pass ftps://$server/$file -O
1

In my case I needed a prompt where the user can enter their credentials.

The most simplistic way to get a prompt for username and password would be the following one-liner:

read -p "Username: " U ; curl -u "$U" <URL> ; unset U

The read command prompts for the username. The -u "$U" parameter tells curl to try to authenticate with the username $U and prompt for the password.

As a bonus the password will only be visible to curl and won't end up in any log or history.

The man page of curl has more details about different authentication modes:

I also like the approach the user "iammyr" takes. It can cover cases where the authentication algorithm of cURL fails:

You should make sure what is the authentication type.

If it is digest authentication , http header is:

GET /xxxxxxxxxxx HTTP/1.1
Host: 192.168.3.142
User-Agent: Go-http-client/1.1
Authorization: Digest username="admin", realm="admin@51200304-49-test", nonce="5.1722929000077545", uri="/xxxxxxxxxxx", response="52d30eba90820f2c4fa4d3292a4a7bbc", cnonce="f11900fe0906e3899e0cc431146512bb", qop=auth, nc=00000001
Accept-Encoding: gzip

you can use --digest option :

 curl --digest -u 'username:password' '
1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy