[keycloak-user] UserStorageProvider for an external database

Soner Dastan son.dastan at gmail.com
Fri Dec 14 11:28:48 EST 2018


Hey Steffen,

There are couple of ways to do it AFAIK.

What we did for our custom UserStorageProvider was to setup a datasource configuration in the existing keycloak datatsources configuration. 
In the <datasources> section of the standalone.xml you have to add following.
We are using an external Postgres DB so my config looks like:

<datasource jndi-name="java:jboss/datasources/yourDB" pool-name="yourDB" enabled="true" use-java-context="true">
    <connection-url>jdbc:postgresql://<ip_or_host_of_your_external DB>:5432/yourDB</connection-url>
    <driver>postgresql</driver>
    <security>
        <user-name>postgres</user-name>
        <password>postgres</password>
    </security>
</datasource>

Then in the <drivers> section (when it is not already defined) you need to add the driver you use. In my case it is Postgres:

<driver name="postgresql" module="org.postgresql.jdbc">
    <xa-datasource-class>org.postgresql.xa.PGXADataSource</xa-datasource-class>
</driver>


In your custom UserStorageProviderFactory ideally in the constructor you can lookup for the datasource:

public UserStorageProviderFactory() throws NamingException {

    InitialContext context = new InitialContext();
    dataSource = (DataSource) context.lookup("java:jboss/datasources/yourDB");

    try {
        log.info("datasource: " +  dataSource.toString());
        log.info("WORKING: " + dataSource.getConnection().isValid(3000));
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

In the create method of your custom factory you can pass the Connection object to your UserStorageProvider:

public UserStorageProvider create(KeycloakSession keycloakSession, ComponentModel componentModel) {
    try {
            return new UserStorageProvider(keycloakSession, componentModel, dataSource.getConnection());
    } catch (SQLException e) {
        throw new RuntimeException("Could not get a connection for DB");
    }
}
In your provider class you can use this connection to do the lookup for users etc. I hope this helps.

Best,
Soner


More information about the keycloak-user mailing list