从Postman访问Keycloak API

23

我曾尝试使用Postman访问Keycloak API,但是显示400错误请求。

我按以下格式调用API:

http://{hostname}:8080/auth/realms/master/protocol/openid-connect/token?username=admin&password=admin&client_id=admin-cli&grant_type=password

在头部中,我已将 content_type 设置为 application/x-www-form-urlencoded

我得到的响应如下所示。

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

有人能帮帮我吗?任何帮助都会受到赞赏。提前谢谢。


你是否使用curl进行了多个应用的Keycloak身份验证?我已经使用curl进行了身份验证,但当我访问另一个应用程序时,我必须重新登录。如何使用Keycloak登录来进行多个应用程序的身份验证? - Joyson
问题在于这是一个GET请求,而Keycloak只接受POST方式的API调用。 - NaN
5个回答

42
有点晚了,但您问的是Postman而不是cURL。 所以您必须将选项放入x-www-form-urlencoded中。 在此输入图片描述

3
谢谢。这对我有用。 我也在请求正文中传递了client_secret。 - Programmer
在我的情况下,需要client_secret,否则它会抛出一个错误。 - Sumit Jindal

12

你可以通过POST客户端调用API

URL - http://localhost:8080/auth/realms/Demo/protocol/openid-connect/token

在上面的URL中,我使用Demo作为我的领域而不是master

ContentType - "Content-Type":"application/x-www-form-urlencoded"

参数

{
"client_secret" : "90ec9638-7647-4e65-ad20-b82df3341084",
"username" : "ankur",
"password" : "123456",
"grant_type" : "password",
"client_id": "app-client"
}

将标题设置如下

输入图像描述在此处

数据需要按照以下方式传递 输入图像描述在此处


5
获取了access_token等参数后,您将如何将这些参数添加到请求资源的每个请求中? - Vishrant

3
您正在使用的 URL 是用于获取令牌的。
获取令牌应该是一个 POST 请求,而您所发送的请求是一个 GET 请求。以下是一个 CURL 示例,说明如何请求 access_token
curl -X POST \
   http://{hostname}:8080/auth/realms/{realm}/protocol/openid-connect/token \
   -H 'Content-Type: application/x-www-form-urlencoded' \
   -d 'username=admin&password=admin&grant_type=password&client_id=admin-cli'

2

我创建了一个Postman集合,以帮助我们开始使用Keycloak API。任何人都可以保存以下JSON并在Postman中导入:

{
"info": {
    "_postman_id": "07a9d691-5b1c-4869-990b-551da29590fe",
    "name": "Keycloak",
    "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
},
"item": [
    {
        "name": "GET REALM",
        "request": {
            "method": "GET",
            "header": [],
            "url": {
                "raw": "{{KEYCLOAK_URL}}admin/realms/{{KEYCLOAK_REALM}}",
                "host": [
                    "{{KEYCLOAK_URL}}admin"
                ],
                "path": [
                    "realms",
                    "{{KEYCLOAK_REALM}}"
                ]
            }
        },
        "response": []
    },
    {
        "name": "GET USERS",
        "event": [
            {
                "listen": "prerequest",
                "script": {
                    "id": "dfda403a-35b8-4704-840d-102eddac32e6",
                    "exec": [
                        ""
                    ],
                    "type": "text/javascript"
                }
            }
        ],
        "protocolProfileBehavior": {
            "disableBodyPruning": true
        },
        "request": {
            "method": "GET",
            "header": [],
            "body": {
                "mode": "urlencoded",
                "urlencoded": []
            },
            "url": {
                "raw": "{{KEYCLOAK_URL}}admin/realms/{{KEYCLOAK_REALM}}/users",
                "host": [
                    "{{KEYCLOAK_URL}}admin"
                ],
                "path": [
                    "realms",
                    "{{KEYCLOAK_REALM}}",
                    "users"
                ]
            }
        },
        "response": []
    }
],
"auth": {
    "type": "bearer",
    "bearer": [
        {
            "key": "token",
            "value": "{{KEYCLOAK_TOKEN}}",
            "type": "string"
        }
    ]
},
"event": [
    {
        "listen": "prerequest",
        "script": {
            "id": "c3ae5df7-b1e0-4af1-988b-c592df3fd98e",
            "type": "text/javascript",
            "exec": [
                "const echoPostRequest = {",
                "  url: pm.environment.get('KEYCLOAK_URL') + 'realms/master/protocol/openid-connect/token',",
                "  method: 'POST',",
                "  header: 'Content-Type:application/x-www-form-urlencoded',",
                "  body: {",
                "    mode: 'urlencoded',",
                "    urlencoded: [",
                "        {key:'username', value:pm.environment.get('KEYCLOAK_USER')}, ",
                "        {key:'password', value:pm.environment.get('KEYCLOAK_PASSWORD')}, ",
                "        {key:'client_id', value:'admin-cli'}, ",
                "        {key:'grant_type', value:'password'}",
                "    ]",
                "  }",
                "};",
                "",
                "var getToken = true;",
                "",
                "if (!pm.environment.get('KEYCLOAK_TOKEN_EXPIRY') || ",
                "    !pm.environment.get('KEYCLOAK_TOKEN')) {",
                "    console.log('Token or expiry date are missing')",
                "} else if (pm.environment.get('KEYCLOAK_TOKEN_EXPIRY') <= (new Date()).getTime()) {",
                "    console.log('Token is expired')",
                "} else {",
                "    getToken = false;",
                "    console.log('Token and expiry date are all good');",
                "}",
                "",
                "if (getToken === true) {",
                "    pm.sendRequest(echoPostRequest, function (err, res) {",
                "    console.log(err ? err : res.json());",
                "        if (err === null) {",
                "            console.log('Saving the token and expiry date')",
                "            var responseJson = res.json();",
                "            pm.environment.set('KEYCLOAK_TOKEN', responseJson.access_token)",
                "    ",
                "            var expiryDate = new Date();",
                "            expiryDate.setSeconds(expiryDate.getSeconds() + responseJson.expires_in);",
                "            pm.environment.set('KEYCLOAK_TOKEN_EXPIRY', expiryDate.getTime());",
                "        }",
                "    });",
                "}"
            ]
        }
    },
    {
        "listen": "test",
        "script": {
            "id": "fdb69bb4-14a5-43b4-97e2-af866643e390",
            "type": "text/javascript",
            "exec": [
                ""
            ]
        }
    }
],
"variable": [
    {
        "id": "698bbb41-d3f9-47f8-9848-4a1c32f9cca4",
        "key": "token",
        "value": ""
    }
],
"protocolProfileBehavior": {}}

我创建了一个预设脚本来获取令牌并设置请求,如下图所示: enter image description here 您应该创建以下环境变量:KEYCLOAK_USER、KEYCLOAK_PASSWORD和KEYCLOAK_URL,其中URL必须是https://{您的keycloak安装}/auth/。

0
您也可以使用CURL获取信息。
curl -L -X POST 'http://<serveraddress>/auth/realms/<realmname>/protocol/openid-connect/token' -H 'Content-Type: application/x-www-form-urlencoded' --data-urlencode 'client_id=<clientid>' --data-urlencode 'grant_type=password' --data-urlencode 'client_secret=<clientsecret>' --data-urlencode 'scope=openid' --data-urlencode 'username=<username>' --data-urlencode 'password=<password>'

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接