我如何通过授权头使用cURL?(可在/usr/bin/curl中执行)。


当前回答

如果在调用时没有令牌,则必须进行两次调用,一次获取令牌,另一次从响应中提取令牌,请注意

Grep令牌| cut -d, -f1 | cut -d\" -f4

因为它是处理从响应中提取令牌的部分。

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()

提取令牌后,您可以使用令牌进行后续调用,如下所示。

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 

其他回答

FWIW,在Mac OS上,我发现我需要用引号包围目标url时,它包含查询参数,例如,

curl -H "Authorization: Token xxxxxxxxxxxxxx" "https://www.example.com/?param=myparam"

只是添加,所以你不需要点击:

curl --user name:password http://www.example.com

或者如果你试图为OAuth 2发送身份验证:

curl -H "Authorization: OAuth <ACCESS_TOKEN>" http://www.example.com

从curl 7.61.0开始,您可以使用——oauth2-bearer <token>选项来设置正确的承载授权标头。

(对于那些正在寻找php-curl答案的人)

$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);

这招对我很管用:

curl -H "Authorization: Bearer xxxxxxxxxxxxxx" https://www.example.com/