0

I want to transfer the value of one curl command that gets a token to another curl command. keeping the same value. This code will get a token value but when using another curl command it seems to make the token invalid:

token=$(curl -k -X 'POST' \
 '<URL>/api/api-token-auth/' \
 -H 'accept: application/json' \
 -H 'Authorization: Basic dGVzdGFkbWluOlBhc3N3b3JkJDE=' \
 -H 'Content-Type: application/x-www-form-urlencoded' \
 -d 'username=testadmin&password=Password%241' | sed -n '/ *"token": *"/ {s///; s/".*//; p;} ') echo $token && curl -k -X 'GET' \
 '<URL>/api/assessments/' \
 -H 'accept: application/json' \
 -H 'Authorization: Token $token' 

I am using Linux.

2 Answers 2

1

One possible problem I can see is: the generated token might contain characters that get removed with sed. So you alter the token and it could not be used further.

In that case, I would suggest using jq (might have to be installed on your system) to parse json instead of fixing the sed call.

Since I don't know what service you are using, I can't tell the exact syntax of the jq call. One wild guess would be:

jq --monochrome-output --raw-output --unbuffered '"\(.token)"'

Substitute the sed with my jq example and see if that brings you closer.

(not sure, if this qualifies as an answer, but I'm also new here and are not yet allowed to comment)

0

this works for me

token=$(curl 'https://example.com/v1.2/auths/login' \
-H 'Accept: application/json, text/plain, */*' \
-H 'Content-Type: application/json' \
--data-raw '{"username":"username","password":"password"}'  | jq '.token')
echo $token

#to remove the double quotes from the token string 
token=`sed -e 's/^"//' -e 's/"$//' <<<"$token"`  

 curl 'https://example.com/otherapi' \
  -H 'Accept: application/json, text/plain, */*' \
  -H "Authorization: Bearer $token" 

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .