通过 cURL 获取访问令牌

daf*_*ero 3 curl keycloak

简单的问题:

为什么下面的代码有效......(它返回访问令牌就好了)

curl --data "grant_type=client_credentials&client_id=synchronization_tool&client_secret=8f6a6e73-66ca-4f8f-1234-ab909147f1cf" http://localhost:8080/auth/realms/master/protocol/openid-connect/token 
Run Code Online (Sandbox Code Playgroud)

而这个没有?

curl -d  '{"grant_type":"client_credentials","client_secret":"8f6a6e73-66ca-4f8f-1234-ab909147f1cf","client_id":"synchronization_tool"}' http://localhost:8080/auth/realms/master/protocol/openid-connect/token -H "Content-Type: application/json"
Run Code Online (Sandbox Code Playgroud)

它给了我:

"error":"invalid_request","error_description":"Missing form parameter: grant_type"}
Run Code Online (Sandbox Code Playgroud)

它们不应该是两个完全类似的请求吗?

Ces*_*lis 12

卷曲命令:

curl \
  -d "client_id=account" \
  -d "client_secret=YOUR_SECRET" \
  -d "grant_type=client_credentials" \
  "http://localhost:9080/auth/realms/myrealm/protocol/openid-connect/token"
Run Code Online (Sandbox Code Playgroud)

回复:

{
  "access_token": "...redacted...",
  "expires_in": 3600,
  "refresh_expires_in": 0,
  "token_type": "Bearer",
  "not-before-policy": 0,
  "scope": "profile email"
}
Run Code Online (Sandbox Code Playgroud)


Anu*_*ary 10

curl -d 'client_id=xxx' -d 'username=xxx' -d 'password=xxx' -d 'grant_type=password' 'http://localhost:8080/auth/realms/YOUR_REALM_NAME/protocol/openid-connect/token' | python -m json.tool
Run Code Online (Sandbox Code Playgroud)

这对我有用,它会给你access_tokensession_token

  • 您可能还需要 `-d 'client_secret=your_client_secret'` (2认同)

daf*_*ero 7

好吧,看来这些 cURL 查询并不相似。

此外,端点 http://localhost:8080/auth/realms/master/protocol/openid-connect/token 不理解 JSON,它只接受 x-www-form-urlencoded 查询。


小智 7

使用 Keycloak 17.0+ 时请注意。您必须/auth在端点中省略,因为 API 已更改。因此,您需要执行以下命令:

curl -d 'client_id=xxx' -d 'username=xxx' -d 'password=xxx' -d 'grant_type=password' \ 
  'http://localhost:8080/realms/YOUR_REALM_NAME/protocol/openid-connect/token'
Run Code Online (Sandbox Code Playgroud)

请参阅此处了解原始问题/答案。