Keycloak - 使用 APIcalls 从用户添加/删除领域角色

Ton*_*ony 3 keycloak

将 userRepresentation.id 传递给 keycloakServerURL + "/auth/admin/realms/XXXX/users/"+userId+"/role-mappings/realm" 我为某个用户获得这些角色......

[
    {
        "id": "xxxxxxx-1faf-4604-832a-fa7ab7eb4344",
        "name": "uma_authorization",
        "description": "${role_uma_authorization}",
        "composite": false,
        "clientRole": false,
        "containerId": "XXXX"
    },
    {
        "id": "xxxxxxx-ad9f-444e-adf4-be11ab7a3d98",
        "name": "member_paid",
        "description": "Membership Paid",
        "composite": false,
        "clientRole": false,
        "containerId": "XXXX"
    },
    {
        "id": "xxxxx-2d73-48a8-844d-a953cb570270",
        "name": "offline_access",
        "description": "${role_offline-access}",
        "composite": false,
        "clientRole": false,
        "containerId": "XXXX"
    }
]
Run Code Online (Sandbox Code Playgroud)

我不知道应该使用哪个 API 来向用户添加/删除角色。

请您告知我需要使用的 API 是什么

我能找到的最好的是下面这个,但我不知道参数是什么(路径和请求属性应该是)...

public void removeRole(JsonObject userToken, String clientId, String role) throws IOException {

    /auth/admin/realms/XXXX/groups/" + role + "/role-mappings/clients/" + clientId);

    ...
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    con.setRequestMethod("POST");

    con.setRequestProperty("id", clientId);
    con.setRequestProperty("name", role);
    ....
Run Code Online (Sandbox Code Playgroud)

Evi*_*unk 6

端点

获取角色映射:

GET /auth/admin/realms/{Realm}/users/{userid}/role-mappings/realm

添加角色映射:

POST /auth/admin/realms/{Realm}/users/{userid}/role-mappings/realm

删除角色映射:

删除 /auth/admin/realms/{Realm}/users/{userid}/role-mappings/realm

示例 添加角色

你有一个角色,例如testrole用 id命名dc5572a5-b7e0-4c4b-b841-dc88108df70f(当你打开 keycloak 管理 GUI 时,你会在 url 中看到它,或者你用其他一些 RestAPI 请求获取它)

现在我们有一个POST到端点的类型请求,/auth/admin/realms/{Realm}/users/{userid}/role-mappings/realm其主体类型application/json和以下主体值

[
    {
        "id": "dc5572a5-b7e0-4c4b-b841-dc88108df70f",
        "name" : "testrole"
    }
]
Run Code Online (Sandbox Code Playgroud)

成功执行后,您会收到 HTTP-Code 204 => testrole- 角色映射应用于此用户的响应

示例卷曲请求

curl --request POST \
  --url http://localhost/auth/admin/realms/{Realm}/users/{userid}/role-mappings/realm \
  --header 'authorization: Bearer eyJh......h3RLw' \
  --header 'content-type: application/json' \
  --data '[
    {
        "id": "dc5572a5-b7e0-4c4b-b841-dc88108df70f",
        "name" : "testrole"
    }
]'
Run Code Online (Sandbox Code Playgroud)

如果您想再次删除它,只需发送相同的请求(相同的正文),但使用 HTTP 方法DELETE而不是POST

如果这解决了您的问题,请现在告诉我