簡體   English   中英

如何在不使用 rest admin api 的情況下以編程方式(java)更新 keycloak 的用戶詳細信息?

[英]How can I update keycloak's user details programmatically (java), without using rest admin api?

我想更新用戶詳細信息。 例如,我從 keycloak 管理控制台在“演示”領域創建了用戶(k1)。 我有一個 java 客戶端,我想更新用戶(k1)的詳細信息。 更改用戶 k1 的電子郵件地址。

我確實使用了管理客戶端(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();
    }
}

但我想在不使用管理客戶端的情況下做同樣的事情。

您可以使用 jsoup-1.6.0.jar 來更新任何用戶的詳細信息,如下所示。

public boolean updateAccountDetails(String name, String value) 
{
String url= getKeycloakAdapter().getDeployment().getAccountUrl();

Document document = Jsoup.connect(url).get();
if (document != null) {
  String formQuery = String.format("form[action^=%s]", url);
  Elements form = document.select(formQuery);
  if (!form.isEmpty()) {
    Elements inputs = form.select("input[value], input:not([disabled])");
    Element saveAction = form.select("button[value=Save]").first();
    inputs.add(saveAction);
    Map<String, String> mandatoryArguments = new HashMap<>();
    for (Element input : inputs) {
      mandatoryArguments.put(input.attr("name"), input.attr("value"));
    }
    mandatoryArguments.put(attributeName, newValue);
    Response response = Jsoup.connect(accountUrl)
        .data(mandatoryArguments)
        .method(Method.POST)
        .execute();

    Document finalDoc = response.parse();
    if (finalDoc != null) {
      Elements finalForm = finalDoc.select(formQuery);
      if (finalForm != null) {
        String newValueQuery = String.format("input[name=%s], input[value=%s]", name, value);
        Elements finalInputs = finalForm.select(newValueQuery);
        if (finalInputs != null) {
          return !finalInputs.isEmpty();
        }
      }
    }
  }
}
throw new IOException("Account page not found");

}

我使用以下方法做到了。

    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", "5somebody@gmail.com"));
    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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM