Home > Enterprise >  Piping stdin to a cURL header
Piping stdin to a cURL header

Time:12-02

I am trying to read get an authentication token from a Keycloak endpoint and use it to access another resource. Getting the token is not an issue, but passing it along in the header of another request is turning out to be an impossible feat, at least in a single command:

curl \
    -X POST \
    -d 'client_id=app' \
    -d 'username=username' \
    -d 'password=password' \
    -d 'grant_type=password' \
    -d "client_secret=$APP_SECRET" \
    'http://localhost:9000/auth/realms/realm/protocol/openid-connect/token' \
| \
jq -r '.access_token' \
| \
curl \
    -X GET \
    -H "Accept: application/json" \
    -H "Authorization: Bearer @-" \ # <- read header value from stdin
    -u "username:password" \
    "http://localhost:8080/app/api/"

What might be an alternative way of achieving this?

CodePudding user response:

Instead of creating a complex command, why not split it into 2 actions:

  1. Save the token to a variable
  2. Pass the variable to the header

# Get token
token=$(curl \
    -X POST \
    -d 'client_id=app' \
    -d 'username=username' \
    -d 'password=password' \
    -d 'grant_type=password' \
    -d "client_secret=$APP_SECRET" \
    'http://localhost:9000/auth/realms/realm/protocol/openid-connect/token' \
| jq -r '.access_token')

# Send request
curl \
    -X GET \
    -H "Accept: application/json" \
    -H "Authorization: Bearer $token" \
    -u "username:password" \
    "http://localhost:8080/app/api/"
  • Related