gpt4 book ai didi

java - Keycloak 创建用户角色

转载 作者:行者123 更新时间:2023-11-29 04:32:57 26 4
gpt4 key购买 nike

我已经将新用户和角色都插入到 keycloak 中。但是我如何连接用户和角色实体,如用户角色

Keycloak kc = KeycloakBuilder.builder()
.serverUrl("http://localhost:8080/auth")
.realm("master")
.username("admin")
.password("admin")
.clientId("admin-cli")
.resteasyClient(
new ResteasyClientBuilder()
.connectionPoolSize(10).build()
).build();
//creating role
RoleRepresentation roleRepresentation = new RoleRepresentation();
roleRepresentation.setName("latest_role");
kc.realm("master").roles().create(roleRepresentation);
//creating user
UserRepresentation user = new UserRepresentation();
user.setUsername("anoop");
user.setFirstName("anoop");
user.setLastName("anoop");
user.setEnabled(true);
user.setCredentials(Arrays.asList(credential));
kc.realm("master").users().create(user);

最佳答案

这似乎不是一个微不足道的问题。通常我希望 user.setRealmRoles(roleRepresentation) 中有此功能,例如 this example .但这对我不起作用。

相反,我使用此函数将 roleRepresentation 添加到 user

RoleRepresentation savedRoleRepresentation = kc.realm("master").roles()
.get("latest_role").toRepresentation();
kc.realm("master").users().get(userId).roles().realmLevel()
.add(asList(savedRoleRepresentation));

完整代码:

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

RoleRepresentation roleRepresentation = new RoleRepresentation();
roleRepresentation.setName("latest_role");
kc.realm("Test").roles().create(roleRepresentation);

UserRepresentation user = new UserRepresentation();
user.setUsername("test");
user.setFirstName("test");
user.setLastName("test");
user.setEnabled(true);
user.setCredentials(Arrays.asList(credential));

Response response = kc.realm("Test").users().create(user);
String userId = getCreatedId(response);

System.out.println("Testuser created.... verify in keycloak!");

RoleRepresentation savedRoleRepresentation = kc.realm("Test").roles()
.get("latest_role").toRepresentation();
kc.realm("Test").users().get(userId).roles().realmLevel()
.add(asList(savedRoleRepresentation));


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

编辑:

似乎没有为用户保存凭据。要强制 keycloak 保存它们,您必须使用以下方法重置密码:

UserResource userResource = kc.realm("Test").users().get(userId);
userResource.resetPassword(credential);

关于java - Keycloak 创建用户角色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43038230/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com