2

Using a postman as a base, I have a curl request here and I'm trying to return the access token.

AUTHORIZATION=$(curl --location --request POST 'https://some.url/oauth2/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode "grant_type=$GRANT_TYPE" \
--data-urlencode "client_id=$CLIENT_ID" \
--data-urlencode "client_secret=$CLIENT_SECRET"\)

When I echo I get an output like:

{"access_token":"16WkRKbVpHWXlZekJsWVd...","token_type":"Bearer","expires_in":14400}

I want to extract the access_token and use in other parts of my script. I've tried the adding jq .access_token -r as seen below, but I'm just returning a null variable.

AUTHORIZATION=$(curl --location --request POST 'https://some.url/oauth2/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode "grant_type=$GRANT_TYPE" \
--data-urlencode "client_id=$CLIENT_ID" \
--data-urlencode "client_secret=$CLIENT_SECRET"\
-s \
| jq .access_token -r)

Solutions here: extract token from curl result by shell script advise saving to file and grepping on it. I don't really want to save a token to a file if I can avoid it.

Hofbr
  • 868
  • 9
  • 31

2 Answers2

1

It looks like you flipped the parameter name and value when calling jq. I think it should be:

jq -r .access_token

not jq .access_token -r

Other than that your solution looks fine.

Michal Trojanowski
  • 10,641
  • 2
  • 22
  • 41
1

Step 1. Save the response in a variable

AUTHORIZATION=$(curl --location --request POST 'https://some.url/oauth2/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode "grant_type=$GRANT_TYPE" \
--data-urlencode "client_id=$CLIENT_ID" \
--data-urlencode "client_secret=$CLIENT_SECRET"\)

Step 2 use jq.

AUTHORIZATION = `jq '.access_token' <<< "$AUTHORIZATION"`

Step 3 eliminate the quotes.

AUTHORIZATION=`echo "$AUTHORIZATION" | tr -d '"'`.