3

I need to create a shell script that calls my login API via curl. The script should be able to store and process the response from curl api call.

myscript.sh

#!/bin/bash

echo "Extract bearer token from curl calling login api"
echo
# Check cURL command if available (required), abort if does not exists
type curl >/dev/null 2>&1 || { echo >&2 "Required curl but it's not installed. Aborting."; exit 1; }
echo

PAYLOAD='{"email": "[email protected]", "password": "secret"}'

curl -s --request POST -H "Content-Type:application/json"  http://acme.com/api/authentications/login --data "${PAYLOAD}"

My problem in the given script is:

  1. it does not get the response of curl calling the API.
  2. From the response json, get only the token value.

Sample Login API response:

{
  "user": {
    "id": 123,
    "token": "<GENERATED-TOKEN-HERE>",
    "email": "[email protected]",
    "refreshToken": "<GENERATED-REFRESH-TOKEN>",
    "uuid": "1239c226-8dd7-4edf-b948-df2f75508888"
  },
  "clientId": "abc12345",
  "clientSecretKey": "thisisasecret"
}

I only need to get the value of token and store it in a variable... I will use token value in other curl api call as bearer token.

What do I need to change in my script to extract the token value from the response of curl api call?

Thanks!

2 Answers 2

6

Your curl statement has an error in it. You are executing it with the target URL as an header field:

curl --request POST -H "Content-Type:application/json" -H http://acme.com/api/authentications/login --data "${PAYLOAD}"
                                                       ^
                                                       |
                                                   Remove this header flag

Also the silent -s flag helps when curl is executed from scripts:

-s, --silent Silent or quiet mode. Don't show progress meter or error messages. Makes Curl mute.

Afterwards you could store the data in a variable and execute a regular expression on it to extract the token you need for further processing.

The complete script could look like the following:

#!/bin/bash

echo "Extract bearer token from curl calling login api"
echo
# Check cURL command if available (required), abort if does not exists
type curl >/dev/null 2>&1 || { echo >&2 "Required curl but it's not installed. Aborting."; exit 1; }
echo

PAYLOAD='{"email": "[email protected]", "password": "secret"}'

RESPONSE=`curl -s --request POST -H "Content-Type:application/json" http://acme.com/api/authentications/login --data "${PAYLOAD}"`

TOKEN=`echo $RESPONSE | grep -Po '"token":(\W+)?"\K[a-zA-Z0-9._]+(?=")'`

echo "$TOKEN" # Use for further processsing
Sign up to request clarification or add additional context in comments.

6 Comments

I am having problem with regular expressions, please see regexr.com/4eccp I cannot extract just the value of token.
Try the following regex instead: "token":(\W+)?"\K[a-zA-Z0-9._]+(?="). The online tool you provided uses JavaScript regex syntax, grep uses Perl regex. Try this with regex101.com In addition: Be careful with posting JWT tokens here. It contains confidential information when pasted e.g. on jwt.io
If I hard code RESPONSE='<COPIED_RESPONSE_FROM_CURL_CALL>'... regular expression works. but if I use RESPONSE='<CURL_CALL>' it does not return anything (Token is blank).
It is really close, regexp works if I hard code the response.. but if I call curl... response looks correct... but regexp does not work.. it cannot return the token (empty/blank)
@PakiPat the closing single quote was missing. I edited my original post. Thanks!
|
0

An alternate solution to parsing JSON with regex is jq :

echo '{ "user": { "id": 123, "token": "<GENERATED-TOKEN-HERE>", "email": "[email protected]", "refreshToken": "<GENERATED-REFRESH-TOKEN>", "uuid": "1239c226-8dd7-4edf-b948-df2f75508888" }, "clientId": "abc12345", "clientSecretKey": "thisisasecret" }' | jq -r '.user.token'

1 Comment

I am afraid Installing other command is not an option (jq) on my case

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.