From 0a8ee703f32dd6fad6172a2bf9af0401a8640cac Mon Sep 17 00:00:00 2001 From: Alexandre Rousseau Date: Sun, 30 Jul 2023 09:22:01 +0200 Subject: [PATCH] Use `jq` to build payload Building JSON by hand is dangerous. It was possible to have bad behavior and also execute malicious code from `$USERNAME` or `$PASSWORD`. It's safer to use `jq` to build the payload. --- curl_command/curl_command_examples_get_token.sh | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/curl_command/curl_command_examples_get_token.sh b/curl_command/curl_command_examples_get_token.sh index 3877c2e..56a5648 100644 --- a/curl_command/curl_command_examples_get_token.sh +++ b/curl_command/curl_command_examples_get_token.sh @@ -11,8 +11,14 @@ AUTH_URL="https://example.com/auth" USERNAME="user" PASSWORD="pass" +# Build the JSON payload using jq +PAYLOAD=$(jq --null-input \ + --arg username "$USERNAME" \ + --arg password "$PASSWORD" \ + '{ "username": $username, "password": $password }') + # Use curl to authenticate and obtain a token -TOKEN=$(curl -s -X POST -H "Content-Type: application/json" -d '{"username": "'"$USERNAME"'", "password": "'"$PASSWORD"'"}' $AUTH_URL | jq -r '.token') +TOKEN=$(curl -s -X POST -H "Content-Type: application/json" -d "$PAYLOAD" "$AUTH_URL" | jq -r '.token') # Check if the token was obtained successfully if [ -z "$TOKEN" ]; then @@ -24,4 +30,4 @@ fi RESOURCE_URL="https://example.com/resource" # Use curl with the token to access the resource -curl -s -H "Authorization: Bearer $TOKEN" $RESOURCE_URL +curl -s -H "Authorization: Bearer $TOKEN" "$RESOURCE_URL"