3

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.

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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 '"'`.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.