我想更新用户详细信息。例如我从keycloak管理控制台的“演示”领域中创建了user(k1)。我有一个Java客户端,我想更新user(k1)详细信息。更改用户k1的电子邮件地址。
我确实使用了Admin客户端(Rest API),如下所示。
public void updateEmail(final String newEmailAddress) {
try {
final AccessToken accessToken = getToken();
Keycloak keycloak = KeycloakBuilder.builder().serverUrl(this.getDeployment().getAuthServerBaseUrl())
.realm(this.getDeployment().getRealm()).username("k1").password("123").clientId(ADMIN_CLIENT)
.resteasyClient(new ResteasyClientBuilder().connectionPoolSize(10).build()).build();
UserResource userResource = keycloak.realm(this.getDeployment().getRealm()).users()
.get(accessToken.getSubject());
UserRepresentation user = userResource.toRepresentation();
user.setEmail(newEmailAddress);
userResource.update(user);
} catch (Exception exception) {
exception.printStackTrace();
}
}
但是我想做同样的事情而不使用管理客户端。
最佳答案
我做到了使用以下方法。
public void updateEmail(final String newEmailAddress)
throws ClientProtocolException, IOException, HttpFailure, VerificationException {
List<NameValuePair> formparams = new ArrayList<>();
formparams.add(new BasicNameValuePair("stateChecker", "QW1iwts0YS8pC0JDosACq-2ZAJHtTW8HWN7KSgTV8rc"));
formparams.add(new BasicNameValuePair("email", "[email protected]"));
formparams.add(new BasicNameValuePair("firstName", "1some"));
formparams.add(new BasicNameValuePair("lastName", "1body"));
KeycloakDeployment deployment = this.getDeployment();
HttpPost post = new HttpPost("http://localhost:8080/auth/realms/demo/account/");
ClientCredentialsProviderUtils.setClientCredentials(deployment, post, formparams);
post.setHeader("Accept", "application/json");
post.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
post.setHeader("Authorization", "Bearer " + this.getTokenString(10, TimeUnit.SECONDS));
UrlEncodedFormEntity form = new UrlEncodedFormEntity(formparams, "UTF-8");
post.setEntity(form);
HttpResponse response = deployment.getClient().execute(post);
if (response.getStatusLine().getStatusCode() == 200) {
print(response.getEntity().getContent());
} else {
print(response.getEntity().getContent());
System.out.println(response.getStatusLine().toString());
}
}
要完成上述操作,我需要如下更改我的account.ftl(位于*:* \ keycloak-demo-3.1.0.Final \ keycloak \ themes \ base \ account \ account.ftl)
<#if stateChecker??>
<input type="hidden" id="stateChecker" name="stateChecker" value="${stateChecker?html}">
<#else>
<input type="hidden" id="stateChecker" name="stateChecker" value=" ">
</#if>
更改背后的原因是,我收到如下错误:
无法处理模板:org.keycloak.theme.FreeMarkerException:无法处理模板account.ftl
关于java - 如何在不使用rest admin api的情况下以编程方式(java)更新keycloak的用户详细信息?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44675383/