使用Java以编程方式在keycloak 4.8.3中创建用户

时间:2019-03-30 10:08:00

标签: java spring-boot keycloak

我想通过keycloak管理员客户端创建一个用户,但是我得到了:

  

线程“ main”中的异常javax.ws.rs.ProcessingException:           javax.ws.rs.BadRequestException:HTTP 400错误请求

标题,我希望返回创建成功的用户,但它会产生400错误的请求错误

String serverUrl = "http://localhost:8180/auth";
String realm = "demo";
String clientId = "idm-client";
String clientSecret = "a200cdf6-ad72-4f6c-af73-5b8e1cc48876";

Keycloak keycloak = KeycloakBuilder.builder() 
    .serverUrl(serverUrl) //
    .realm(realm) //
    .grantType(OAuth2Constants.CLIENT_CREDENTIALS) //
    .clientId(clientId) //
    .clientSecret(clientSecret).build();

// Define user
UserRepresentation user = new UserRepresentation();
user.setEnabled(true);
user.setUsername("tester1");
user.setFirstName("First");
user.setLastName("Last");
user.setEmail("tom+tester1@tdlabs.local");
user.setAttributes(Collections.singletonMap("origin", 
Arrays.asList("demo")));

// Get realm
RealmResource realmResource = keycloak.realm(realm);
UsersResource userRessource = realmResource.users();

// Create user (requires manage-users role)
Response response = userRessource.create(user);
System.out.println("Repsonse: " + response.getStatusInfo());

产生错误的行是:

Response response = userRessource.create(user);

1 个答案:

答案 0 :(得分:0)

如果您从以下位置更改代码,则可以创建用户:

KeyPaths

收件人:

String clientId = "idm-client";
String clientSecret = "a200cdf6-ad72-4f6c-af73-5b8e1cc48876";

Keycloak keycloak = KeycloakBuilder.builder() 
    .serverUrl(serverUrl) //
    .realm(realm) //
    .grantType(OAuth2Constants.CLIENT_CREDENTIALS) //
    .clientId(clientId) //
    .clientSecret(clientSecret).build();

另请参阅: Keycloak Server Developer Guide - 2.2. Example using Java