Home > Net >  curl set dynamic header token throws invalid key
curl set dynamic header token throws invalid key

Time:02-03

Im trying to hit a rest api with token in header.

apikeyName="$(date ' %s')"
key=$(curl -k -X POST -H "Content-Type: application/json" \
                    -d '{"name":"'$apikeyName'", "role": "Admin"}' \
                    http://admin:admin@localhost:3000/api/auth/keys | jq '.key')

echo $key
# # Alerting API
curl -k -X GET 'http://localhost:3000/api/alert-notifications' -H 'Authorization: Bearer '$key'';

Terminal output

"eyJrIjoiaWJPaDFFZXZMeW1RYU90NUR4d014T3hYUmR6NDVUckoiLCJuIjoiMTY3NTM1OTc4OCIsImlkIjoxfQ=="
{"message":"invalid API key","traceID":""}

First 1 is the key printing and last one from api response. I tried to hardcode the key and it works.

CodePudding user response:

Short answer: Use jq -r '.key' to extract the key from the json response without adding quotes to it.

Long answer: There is a difference between quotes on the command line and quotes embedded in a variable. Consider:

key='"abcd"'
printf '%s\n' $key "abcd"
# prints:
# "abcd"
# abcd

Quotes on the command line are bash syntax. Bash notes what is being quoted and then removes the quotes from the command line when it's done, thus printf only prints abcd in the second case above.

Quotes inside a variable are plain old data. Bash doesn't do anything with them, so they get passed through to the command like any other data and printf prints "abcd" in the first case.

In your curl case the receiver doesn't expect the key to have quotes embedded in the data. So, curl -blah "keydata" works fine because bash takes the quotes out, but curl -blah $key fails because bash does NOT remove the embedded quotes.

See also: BashParser

  • Related