如何在 KeyCloak 中使用 REST Post 请求创建用户?

How to Create User with REST Post Request in KeyCloak?

您好,我尝试通过 API 请求从 KeyCloak 创建或获取用户。

我的Keycloak客户端配置如下:

Client Protocol: openid-connect
Access Type: confidential
Direct Access Grants Enabled: ON
Service Accounts Enabled: ON

"MyRealm" -> "Cients" -> "Service Account Roles""Client Roles" 我添加了 "view-users""manage-users"

在使用 "client-id""client-secret""username""password""grant-type" : "password" 检索访问令牌后工作正常,我尝试以下 REST API 呼叫:

GET http://localhost:8180/auth/admin/realms/MyRealm/users
-Header "Authorization" "Bearer " + {accesstoken}"

但我只返回 {"error":"unknown_error"}

尝试使用

创建用户时相同
POST http://localhost:8180/auth/admin/realms/MyRealm/users
-Header "Authorization" "Bearer " + {accesstoken}"
        "Content-Type"  "application/json"

-Body {"username":"mid",
       "email":"bla@gtestmail.com", 
       "firstName":"mi",
       "lastName":"di",
       "enabled":"true"
       }

我是否需要更改 Keycloak 中的任何特定配置才能获取或创建用户?

您遇到上述错误是因为您的用户没有适当的角色来查询或管理用户。您只使用 Service Account Roles 向您的客户添加了角色。

请检查您是否已将上述屏幕截图中提到的角色添加到您的用户中。如果您正确配置了上述角色,那么您的输出看起来像这样

[
    {
        "id": "2d274b22-4cd7-4711-ae0d-529615309b57",
        "createdTimestamp": 1632647518630,
        "username": "user1",
        "enabled": true,
        "totp": false,
        "emailVerified": false,
        "firstName": "fname1",
        "lastName": "lname1",
        "email": "user1@localhost",
        "attributes": {
            "picture": [
                "https://avatars.githubusercontent.com/u/90400807?s=96&v=4"
            ],
            "myattribute": [
                "myvalue"
            ]
        },
        "disableableCredentialTypes": [],
        "requiredActions": [],
        "notBefore": 0,
        "access": {
            "manageGroupMembership": true,
            "view": true,
            "mapRoles": true,
            "impersonate": false,
            "manage": true
        }
    },
    {
        "id": "9d1ed9d9-73e3-4315-bea3-7132d7557c40",
        "createdTimestamp": 1632977937850,
        "username": "user2",
        "enabled": true,
        "totp": false,
        "emailVerified": false,
        "firstName": "firstName2",
        "lastName": "lastName",
        "email": "user2@localhost",
        "disableableCredentialTypes": [],
        "requiredActions": [
            "UPDATE_PROFILE"
        ],
        "notBefore": 0,
        "access": {
            "manageGroupMembership": true,
            "view": true,
            "mapRoles": true,
            "impersonate": false,
            "manage": true
        }
    }
]