How do I pass authorization header using cURL? ( executable in /usr/bin/curl
).
This question is related to
curl
http-authentication
Just adding so you don't have to click-through:
curl --user name:password http://www.example.com
or if you're trying to do send authentication for OAuth 2:
curl -H "Authorization: OAuth <ACCESS_TOKEN>" http://www.example.com
For HTTP Basic Auth:
curl -H "Authorization: Basic <_your_token_>" http://www.example.com
replace _your_token_
and the URL.
This worked for me:
curl -H "Authorization: Token xxxxxxxxxxxxxx" https://www.example.com/
(for those who are looking for php-curl answer)
$service_url = 'https://example.com/something/something.json';
$curl = curl_init($service_url);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_USERPWD, "username:password"); //Your credentials goes here
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); //IMP if the url has https and you don't want to verify source certificate
$curl_response = curl_exec($curl);
$response = json_decode($curl_response);
curl_close($curl);
var_dump($response);
Be careful that when you using:
curl -H "Authorization: token_str" http://www.example.com
token_str
and Authorization
must be separated by white space, otherwise server-side will not get the HTTP_AUTHORIZATION
environment.
If you don't have the token at the time of the call is made, You will have to make two calls, one to get the token and the other to extract the token form the response, pay attention to
grep token | cut -d, -f1 | cut -d\" -f4
as it is the part which is dealing with extracting the token from the response.
echo "Getting token response and extracting token"
def token = sh (returnStdout: true, script: """
curl -S -i -k -X POST https://www.example.com/getToken -H \"Content-Type: application/json\" -H \"Accept: application/json\" -d @requestFile.json | grep token | cut -d, -f1 | cut -d\\" -f4
""").split()
After extracting the token you can use the token to make subsequent calls as follows.
echo "Token : ${token[-1]}"
echo "Making calls using token..."
curl -S -i -k -H "Accept: application/json" -H "Content-Type: application/json" -H "Authorization: Bearer ${token[-1]}" https://www.example.com/api/resources
Bearer tokens look like this:
curl -H "Authorization: Bearer <ACCESS_TOKEN>" http://www.example.com
Source: Stackoverflow.com