我正在嘗試從 Keycloak 端點讀取獲取身份驗證令牌并使用它來訪問另一個資源。獲取令牌不是問題,但在另一個請求的標頭中傳遞它是不可能的,至少在單個命令中是這樣:
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/"
實作這一目標的另一種方法是什么?
uj5u.com熱心網友回復:
與其創建一個復雜的命令,不如將其拆分為 2 個操作:
- 將令牌保存到變數
- 將變數傳遞給標題
# 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/"
uj5u.com熱心網友回復:
另一個答案提供了更好的解決方案,但這篇文章回答了所提出的字面問題。
您可以使用以下內容:
"Authorization: Bearer $( cat )"
演示:
$ echo foo | printf "%s\n" "Authorization: Bearer $( cat )"
Authorization: Bearer foo
事實上,您可以將整個令牌獲取代碼放在$().
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/"
演示:
$ printf "%s\n" "Authorization: Bearer $( echo foo )"
Authorization: Bearer foo
同樣,我認為這些不如@0stone0 提供的更清晰的解決方案。我發布它們是出于教育目的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/371600.html
