1

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?

sesodesa
  • 1,473
  • 2
  • 15
  • 24

2 Answers2

5

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/"
0stone0
  • 34,288
  • 4
  • 39
  • 64
1

The other answer provides a better solution, but this post answers the literal question asked.

You can use the following:

"Authorization: Bearer $( cat )"

Demo:

$ echo foo | printf "%s\n" "Authorization: Bearer $( cat )"
Authorization: Bearer foo

In fact, you could put the entire token-fetching code inside of $().

curl                              \
    -X GET                        \
    -H "Accept: application/json" \
    -H "Authorization: Bearer $(
        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
    )"                            \
    -u "username:password"        \
    "http://localhost:8080/app/api/"

Demo:

$ printf "%s\n" "Authorization: Bearer $( echo foo )"
Authorization: Bearer foo

Again, I consider these inferior to the clearer solution provided by @0stone0. I am posting them for educational purposes.

ikegami
  • 367,544
  • 15
  • 269
  • 518