POST 从 keycloak 获取访问令牌的请求失败

POST request to get access token from keycloak fails

我正在尝试从 keycloak 的 REST 获取访问令牌-API:

library(jsonlite)
library(httr)

admin_user <- list(
  username = "admin",
  password = "admin",
  grant_type = "password",
  client_id = "admin_cli"
)
tkn01 <- POST(
  "https://www.example.com/auth/realms/master/protocol/openid-connect/token",
  body = toJSON(admin_user),
  add_headers(.headers = c("Content-Type" = "application/x-www-form-urlencoded"))
)

这会导致错误:

rawToChar(tkn01$content)
[1] "{\"error\":\"invalid_request\",\"error_description\":\"Missing form parameter: grant_type\"}"

虽然已经提供grant_type

我也试过 curl:

curl -i -X POST -d '{"username":"admin","password":"admin","grant_type":"password","client_id":"admin_cli"}' https://www.example.com/auth/realms/master/protocol/openid-connect/token
HTTP/1.1 400 Bad Request
Server: nginx/1.17.8
Date: Wed, 09 Dec 2020 16:27:14 GMT
Content-Type: application/json
Content-Length: 84
Connection: keep-alive
Cache-Control: no-store
X-XSS-Protection: 1; mode=block
Pragma: no-cache
X-Frame-Options: SAMEORIGIN
Referrer-Policy: no-referrer
Strict-Transport-Security: max-age=15724800; includeSubDomains
X-Content-Type-Options: nosniff

{"error":"invalid_request","error_description":"Missing form parameter: grant_type"}

您正在 posting JSON 结构,这是错误的。您只需要 post 为 parameters/fields。卷曲示例:

curl -s -X POST \
  --data "scope=${SCOPE}" \
  --data-urlencode "client_id=${CLIENTID}" \
  --data-urlencode "client_secret=${CLIENTSECRET}" \
  --data-urlencode "username=${USERNAME}" \
  --data-urlencode "password=${PASSWORD}" \
  --data-urlencode "grant_type=password" \
  https://www.example.com/auth/realms/master/protocol/openid-connect/token