Home > database >  How to extract bearer token from curl json response and pass it as authorization header a different
How to extract bearer token from curl json response and pass it as authorization header a different

Time:11-02

I am making a call to OAuth API using curl command by passing username,password and getting the bearer token response as JSON which is in the below format.

curl -X POST https://api.mysite.com/oauth/token -u "login:password" 

Response

{
   "token_type:"Bearer",
   "access_token:" "cfdadfa3234sfsdfxx......",
   "issued_at":15234234234,
   "expires_in":953343434,
   "scope": "asdfasd234234234asfasdfasdfaflalsdfkasjfa;sdfassdflj"
}

I need to get only the access_token value which is the bearer token from this curl JSON response and I need to pass as Authorization header to a different apigee gateway hosted api call.

curl -X GET https://apigee.mysite.com/getorderstatus -H "Authroization Bearer ???need to pass bearer token here ???"

How do I parse the JSON and get the bearer token as variable and pass it to the next API call?

I need to do this on the windows server. My environment is only limited to Windows. I can't install packages like jq due to security reason.

CodePudding user response:

The recommended way to extract something from JSON is jq.

However, if you're really sure that the output is always like this, you might

at=$(curl -X POST https://api.mysite.com/oauth/token -u "login:password" | sed -n 's/[ ,"]//g;s/"access_token://p')
curl -X GET https://apigee.mysite.com/getorderstatus -H "$at"

CodePudding user response:

Using sed

$ bearerToken=$(sed -En '/access_token/s/.* "([^"]*).*/\1/p' <(curl --no-progress-meter -X POST https://api.mysite.com/oauth/token -u "login:password"))
$ echo "$bearerToken"
cfdadfa3234sfsdfxx......
$ curl -X GET https://apigee.mysite.com/getorderstatus -H "$bearerToken"
  • Related