简体   繁体   English

如何以编程方式创建keycloak客户端角色并分配给用户

[英]How to create keycloak client role programmatically and assign to user

I want to create keycloak client role programmatically and assign to user created dynamically. 我想以编程方式创建keycloak客户端角色并分配给动态创建的用户。 Below is my code for creating user 以下是我创建用户的代码

UserRepresentation user = new UserRepresentation();
user.setEmail("xxxxx@xxx.com");
user.setUsername("xxxx");
user.setFirstName("xxx");
user.setLastName("m");
user.setEnabled(true);
Response response = kc.realm("YYYYY").users().create(user);

Here is a solution to your request (not very beautiful, but it works): 这是您的请求的解决方案(不是很漂亮,但它的工作原理):

// Get keycloak client
Keycloak kc = Keycloak.getInstance("http://localhost:8080/auth",
                "master", "admin", "admin", "admin-cli");

// Create the role
RoleRepresentation clientRoleRepresentation = new RoleRepresentation();
clientRoleRepresentation.setName("client_role");
clientRoleRepresentation.setClientRole(true);
kc.realm("RealmID").clients().findByClientId("ClientID").forEach(clientRepresentation ->
    kc.realm("RealmID").clients().get(clientRepresentation.getId()).roles().create(clientRoleRepresentation)
);

// Create the user
UserRepresentation user = new UserRepresentation();
user.setUsername("test");
user.setEnabled(true);
Response response = kc.realm("RealmID").users().create(user);
String userId = getCreatedId(response);

// Assign role to the user
kc.realm("RealmID").clients().findByClientId("ClientID").forEach(clientRepresentation -> {
    RoleRepresentation savedRoleRepresentation = kc.realm("RealmID").clients()
            .get(clientRepresentation.getId()).roles().get("client_role").toRepresentation();
    kc.realm("RealmID").users().get(userId).roles().clientLevel(clientRepresentation.getId())
            .add(asList(savedRoleRepresentation));
});

// Update credentials to make sure, that the user can log in
UserResource userResource = kc.realm("RealmID").users().get(userId);
userResource.resetPassword(credential);

With the help method: 使用帮助方法:

private String getCreatedId(Response response) {
    URI location = response.getLocation();
    if (!response.getStatusInfo().equals(Response.Status.CREATED)) {
        Response.StatusType statusInfo = response.getStatusInfo();
        throw new WebApplicationException("Create method returned status " +
                statusInfo.getReasonPhrase() + " (Code: " + statusInfo.getStatusCode() + "); expected status: Created (201)", response);
    }
    if (location == null) {
        return null;
    }
    String path = location.getPath();
    return path.substring(path.lastIndexOf('/') + 1);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM