如何在没有keycloak管理客户端的情况下更新keycloak用户?

时间:2019-09-11 09:22:43

标签: java keycloak

我正在编写自定义REST端点。 当我调用Resource时,我试图通过实例化UserResource类来更新密钥斗篷中的某些用户。 但是,在更新KeycloakTransactionManager中的第一个用户事务后,该事务将关闭,并且在发生异常java.lang.IllegalStateException:在没有事务的情况下无法访问委托。

我试图通过以下方式开始交易: (例如)

KeycloakSession session = ... ; //got it from context
if(!session.getTransactionManager().isActive()){
session.getTransactionManager().begin();
}

但是得到了“ java.lang.IllegalStateException:处于非法状态的事务以进行回滚:FINISHED”,然后是“ java.lang.IllegalStateException:没有与当前线程关联的事务”。

// custom resource class
public class MyResource {

    @Context
    private HttpHeaders headers;

    private MyAdminAuth auth;
    private MyHelper helper;
    private AppAuthManager authManager;
// I've correctly getting session and with open/active transaction
    private KeycloakSession session;

    public MyResource(KeycloakSession session) {
        this.authManager = new AppAuthManager();
        this.session = session;
    }

@Path("sync-users-run")
    @POST
    @NoCache
    @ResponseObject
    public String syncUsersRun(String json) {
        Gson gson = new Gson();
        helper = new MyHelper(authManager, session, headers);
        SyncMain sync = new SyncMain(params, helper);
        String response = gson.toJson(sync.run());
        return response;
    }
}


private boolean updateUserInKeycloak(UserRepresentation existingUser, User newData) {
        existingUser.setEmail(newData.getEmail());
        existingUser.setEnabled(newData.isActive());
        existingUser.setFirstName(newData.getName());
        existingUser.setLastName(newData.getLastName());
        try {
            KeycloakSession session = helper.getSession();

            UserModel user = session.users().getUserById(existingUser.getId(), helper.getRealmFromSession(session));
            UserResource userResource = helper.getInstanceOfUserResource(user, MyAdminAuth.ROLE_ALLOW_SYNC_USERS);

//trying to update user but it works only for the first one
            Response response = userResource.updateUser(existingUser);
            if (response.getStatus() != NO_CONTENT_CODE) {
                return false;
            }
        } catch (IllegalStateException | WebApplicationException e) {
            return false;
        }
        return true;
    }

如何在没有Keycloak管理客户端的情况下正确更新用户? 也许存在更简单正确的方法?

0 个答案:

没有答案