The following examples will go through how to use curl with authentication. For obvious reasons, public APIs do not require authentication but private APIs will require authentication using authorization headers with basic auth, a bearer token header using a JWT (Javascript Web Token), or with a public key X.509 certificate and corresponding private key.
curl authentication with a private key
To authenticate with a private key and certificate using curl, you will need to provide the --key
and --cert
options to your request. The private key must be decrypted in plain text. The provided certificate must contain the corresponding public key.
As an example, using a private key and its corresponding certificate to authenticate, run the following command:
curl -v -GET --key key.pem --cert cert.pem https://example.com
Where -v
is verbose, -GET
is a GET request, --key key.pem
is the key file or path to the private key, --cert cert.pem
is the certificate with the corresponding public key, all followed up by the URL you are sending the request to.
curl authentication with a bearer token JWT
To authenticate with a bearer token using curl, you will need to pass the token in the authorization headers after the key word “Bearer”. This example assumes you have already generated a JWT (JavaScript Web Token).
To pass the bearer token in the authorization header in your curl request, run the following command:
curl -H "Authorization: Bearer your_token" https://example.com
Where -H
is the header option followed by the authorization header containing your JWT bearer token, followed by the URL you are sending your authenticated request to.
curl authentication with basic auth
To authenticate with basic auth using curl, you will need to provide the --user
option with a user name and password separated by a colon. Basic auth is the default, so it is not necessary to use the basic auth header. Note that due to the colon delimiter, a colon is not supported in the username.
As an example, using basic auth to authenticate with curl, run the following command:
curl --user username:password https://example.com
Where --user
is followed by the username and password (colon delimited) with basic auth being the default, then followed by the URL you are sending the authenticated request to.
Leave a Reply