Keycloak-使用API​​调用从用户添加/删除领域角色

时间:2020-02-20 03:34:01

标签: keycloak

传递userRepresentation.id 到keycloakServerURL +“ / auth / admin / realms / XXXX / users /” + userId +“ /角色映射/领域” 我为某个用户获得了这些角色...

[
    {
        "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"
    }
]

我无法弄清楚应该使用哪个API向用户添加角色或从用户删除角色。

请告知我需要使用什么API

我能找到的最好的是下面的那个,但是我不知道参数是什么(Path和request属性应该是)...

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);
    ....

2 个答案:

答案 0 :(得分:5)

端点

获取角色映射:

获取/ 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的代码(打开密钥库管理GUI时,您会在URL中看到它,或者通过其他RestAPI请求来获取它)

现在,我们向端点POST发送了/auth/admin/realms/{Realm}/users/{userid}/role-mappings/realm类型的请求,请求的主体为application/json类型,并具有以下主体值

[
    {
        "id": "dc5572a5-b7e0-4c4b-b841-dc88108df70f",
        "name" : "testrole"
    }
]

成功执行后,您将收到HTTP代码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"
    }
]'

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

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

答案 1 :(得分:0)

基于以上Evil的帖子帮助我...

使用Java(以及具有良好JSON功能的JEE 8)

获取令牌(使用您在密钥斗篷中设置的客户端,该客户端的访问类型为机密并有权访问正确的角色(对于9.0.0,现在更加隐蔽)。

public JsonObject getToken() throws IOException {

    String keycloakServerURL = environmentService.getEnvironmentVariable(EnvironmentService.KEYCLOAK_SERVER);

    String appClientId = environmentService.getEnvironmentVariable(EnvironmentService.APP_CLIENT_ID);
    String appClientSecret = environmentService.getEnvironmentVariable(EnvironmentService.APP_CLIENT_SECRET);

    URL url = new URL(keycloakServerURL + "/auth/realms/XXXXXX/protocol/openid-connect/token");
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    con.setRequestMethod("POST");

    String userpass = appClientId + ":" + appClientSecret;
    String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userpass.getBytes()));

    con.setRequestProperty("Authorization", basicAuth);
    con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    /* Payload support */
    con.setDoOutput(true);
    DataOutputStream out = new DataOutputStream(con.getOutputStream());
    out.writeBytes("grant_type=client_credentials");

    out.flush();
    out.close();

    int status = con.getResponseCode();
    BufferedReader in = new BufferedReader(new 
    InputStreamReader(con.getInputStream()));

    JsonReader jsonReader = Json.createReader(in);
    JsonObject responesAsJson = jsonReader.readObject();

    in.close();
    con.disconnect();

    // Pretty Print of String
    ObjectMapper objectMapper = new ObjectMapper();
    String jSonstring = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(responesAsJson);
    logger.info("Response: " + jSonstring);
    // Pretty Print of String

    logger.info("Response status: " + status);

    //String contentString = responesAsJson.toString();
    //logger.info("Response: " + contentString);

    return responesAsJson;
}

然后添加一个角色(类似于删除-参见上面的帖子)

public void addRole(JsonObject userToken, String userId, RoleRepresentation role) throws IOException {
    String keycloakServerURL = environmentService.getEnvironmentVariable(EnvironmentService.KEYCLOAK_SERVER);


    URL url = new URL(keycloakServerURL + "/auth/admin/realms/XXXXXX/users/" + userId + "/role-mappings/realm");
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    con.setRequestMethod("POST");

    String accessTokenFromUserToken = userToken.getString("access_token");
    con.setRequestProperty("Authorization", "Bearer " + accessTokenFromUserToken);

    con.setRequestProperty("Content-Type", "application/json");

    /* Payload support */
    con.setDoOutput(true);
    DataOutputStream out = new DataOutputStream(con.getOutputStream());
    JsonObject theBodyPart = Json.createObjectBuilder().
            add("id", role.getId()).
            add("name", role.getName()).
            build();
    JsonArray theBodyPartAsArray = Json.createArrayBuilder().add(theBodyPart).build();
    String theBodyPartAsJson = theBodyPartAsArray.toString();
    out.writeBytes(theBodyPartAsJson);      
    out.flush();
    out.close();

    int status = con.getResponseCode();
    logger.info("Response status: " + status);

    con.disconnect();
}