How to perform hibernate queries from org.keycloak.authentication.FormAction

423 views
Skip to first unread message

Nico

unread,
Aug 23, 2021, 3:48:45 AM8/23/21
to Keycloak Dev

Hello,

I have a keycloak extension which reimplement org.keycloak.authentication.FormAction to perform custom action after user creation.

I would like in the success method of this implementation to perform a custom hibernate request. I don't know how to call the EntityManager from there

@Override
public void success(FormContext context) {
        // get attributes
}

I can maybe call it from

    @Override
    public boolean configuredFor(KeycloakSession session, RealmModel realm, UserModel user) {
        EntityManager em = session.getProvider(JpaConnectionProvider.class).getEntityManager();
        return false;
    }

or `setRequiredActions`

But not sure how to use this function and if I can then access EntityManager from `success` ( maybe this can be used to initialized it as private value of the class ?) also not sure theses function are triggered before `sucess`

In the pom of my extension I added this

     <dependency>
         <groupId>org.hibernate</groupId>
         <artifactId>hibernate-core</artifactId>
         <scope>provided</scope>
     </dependency>
     <dependency>
        <groupId>org.keycloak</groupId>
        <artifactId>keycloak-connections-jpa</artifactId>
        <version>1.8.1.Final</version>
        <scope>provided</scope>
    </dependency>

With the EntityManager, I want to request the attributes tables, to get the highest value in the DB for a specific attribute key. I want to perform this request from the entityManager `select max(value) from USER_ATTRIBUTE where name = "mid.id";` I will have then to propose a new value for my new user and to flush the value in the attribute of the new user. I don't know if it is possible to do it in a synchronize way

Thanks for any help,

Regards,

Axel.

Nico

unread,
Aug 23, 2021, 9:48:06 AM8/23/21
to Keycloak Dev
I'm trying this right now.

I hope it will works

    @Override
    public void success(FormContext context) {
        EntityManager entityManager = context.getSession().getProvider(JpaConnectionProvider.class).getEntityManager();
       
        Integer maxMidId = entityManager.createQuery("select max(ua.value) from UserAttributeEntity ua where name='mid.id'", Integer.class).getSingleResult();

Nico

unread,
Aug 26, 2021, 5:01:04 PM8/26/21
to Keycloak Dev
So, it works

I hope this will help some users
Reply all
Reply to author
Forward
0 new messages