4

我使用的示例 Java 代码:

public static AjaxResponse createUser(User newUser) {

    Keycloak keycloak = Keycloak.getInstance(
            SERVER_URL,
            REALM,
            USERNAME,
            PASSWORD,
            CLIENT_ID);

    // Get Realm
    RealmResource realmResource = keycloak.realm(REALM);
    UsersResource userResource = realmResource.users();

    // Create User Representation
    UserRepresentation user = getUserRepresentation(newUser);

    // Create user (requires manage-users role)
    try {
        System.out.println("Username: {}", userResource.get("USER-ID-HERE").toRepresentation().getUsername());            
        System.out.println("Count: " + userResource.count());
        Response response = userResource.create(user);
        System.out.println("Response: " + response.getStatusInfo());
        System.out.println("Response: " + response.getStatus());
        System.out.println("Response: " + response.getMetadata());

    } catch (Exception e) {
        System.out.println(ExceptionUtils.getStackTrace(e));
        return new AjaxResponse("Fail", false);
    }

    return new AjaxResponse("Successful User Creation", true);
}

private static UserRepresentation getUserRepresentation(User newUser) {

    UserRepresentation user = new UserRepresentation();
    user.setEnabled(true);
    user.setUsername(newUser.getUsername());
    user.setFirstName(newUser.getFirstName());
    user.setLastName(newUser.getLastName());
    user.setEmail(newUser.getEmail());

    CredentialRepresentation credentialRepresentation = new CredentialRepresentation();
    credentialRepresentation.setTemporary(true);
    credentialRepresentation.setType(CredentialRepresentation.PASSWORD);
    credentialRepresentation.setValue(newUser.getUsername());
    user.setCredentials(Collections.singletonList(credentialRepresentation));

}

运行代码时得到的响应:

Username: USERNAME Correctly Identified here
Count: 98
Response: Conflict
Response: 409
Response: [Connection=keep-alive,Content-Length=46,Content-Type=application/json,Date=Tue, 03 Jul 2018 15:27:58 GMT,Server=WildFly/10,X-Powered-By=Undertow/1]`

一些想法: 我添加了计数,以确定整个连接是否有效。而且似乎返回的计数是正确的。所以我成功连接到keycloak,但是当我尝试创建用户时出现了其他问题。

我的 pom.xml 中的依赖项

    <dependency>
        <groupId>org.keycloak</groupId>
        <artifactId>keycloak-servlet-filter-adapter</artifactId>
        <version>3.2.1.Final</version>
    </dependency>
    <dependency>
        <groupId>org.keycloak</groupId>
        <artifactId>keycloak-admin-client</artifactId>
        <version>3.2.1.Final</version>   (Have also tried 3.1.0.Final and 3.2.0.Final)
    </dependency>
    <dependency>
        <groupId>org.jboss.resteasy</groupId>
        <artifactId>resteasy-client</artifactId>
        <version>3.1.4.Final</version>
    </dependency>
    <dependency>
        <groupId>org.jboss.resteasy</groupId>
        <artifactId>resteasy-jackson2-provider</artifactId>
        <version>3.1.4.Final</version>
    </dependency>
    <dependency>
        <groupId>org.jboss.resteasy</groupId>
        <artifactId>resteasy-jaxrs</artifactId>
        <version>3.1.4.Final</version>
    </dependency>

据我了解,这些依赖项也是相关的:

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>${jackson-version}</version>
    </dependency>

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>${jackson-version}</version>
    </dependency>

其他信息:

我使用的 Keycloak 版本:3.2.0

Keycloak API 可以在这里找到

有关 HTTP 409 代码的更多信息,请参见此处

我将不胜感激任何帮助或任何指导。注意 凭据和所有变量都已检查过一次、两次、三次和 10 次。我一直在寻找一个完整的工作示例。但是大多数都没有指定所需的依赖项,因此我的代码失败了。

注意:我也在使用 Tomcat-8,并且我正在深入研究这个问题。我看到Tomcat8可能有一些特殊的配置。请注意,我的网络应用程序的身份验证登录注销已经按预期工作。

4

3 回答 3

7

我终于让它工作了。这是供将来参考的解决方案。

UserRepresentation userRepresentation = new UserRepresentation();
userRepresentation.setUsername("randomUser");
Response response = usersResource.create(userRepresentation);
logger.info("Response |  Status: {} | Status Info: {}", response.getStatus(), response.getStatusInfo());
String userId = response.getLocation().getPath().replaceAll(".*/([^/]+)$", "$1");
UserResource userResource = usersResource.get(userId);

然后我用更多信息更新 userResource。

于 2018-07-06T08:45:00.330 回答
0

409 冲突 http 状态给出了提示。

Keycloak 创建用户,如果用户名或电子邮件被重用,通常会返回冲突。检查以确保正在创建的资源包含与已在领域中注册的资源不同的用户名和电子邮件。

简单的检查方法: - 登录管理控制台 - 导航到领域 - 导航到用户选项卡 - 输入用户名并搜索或电子邮件并搜索

于 2018-07-03T18:49:40.227 回答
0
@Override
public UserDto registerNewUserAccount(final UserDto accountDto) {
    String keycloakPassword = accountDto.getPassword();

    accountDto.setPassword(passwordEncoder.encode(accountDto.getPassword()));
    accountDto.setEnabled(1);
    UserDto user = userRepository.save(accountDto);

    AuthorityDto role = new AuthorityDto();
    role.setUserName(accountDto.getLogin());
    role.setAuthority("ROLE_USER");

    authorityRepository.save(role);

    Keycloak kc = Keycloak.getInstance(
            "https://www.zdslogic.com/keycloak/auth",  /your server
            "zdslogic",  //your realm
            "richard.campion", //user 
            "Changit", //password
            "admin-cli"); //client


    CredentialRepresentation credential = new CredentialRepresentation();
    credential.setType(CredentialRepresentation.PASSWORD);
    credential.setValue(keycloakPassword);

    UserRepresentation keycloakUser = new UserRepresentation();
    keycloakUser.setUsername(accountDto.getLogin());
    keycloakUser.setFirstName(accountDto.getFirstName());
    keycloakUser.setLastName(accountDto.getLastName());
    keycloakUser.setEmail(accountDto.getEmail());
    keycloakUser.setCredentials(Arrays.asList(credential));
    keycloakUser.setEnabled(true);
    keycloakUser.setRealmRoles(Arrays.asList("user"));

    // Get realm
    RealmResource realmResource = kc.realm("zdslogic");
    UsersResource usersRessource = realmResource.users();

    // Create Keycloak user
    Response result = null;
    try {
        result = usersRessource.create(keycloakUser);
    } catch(Exception e) {
        System.out.println(e);
    }

    if (result==null || result.getStatus() != 201) {
        System.err.println("Couldn't create Keycloak user.");
    }else{
        System.out.println("Keycloak user created.... verify in keycloak!");
    }

    return user;

}
于 2020-12-10T17:18:11.190 回答