Monday, March 12, 2018

Keycloak MYSQL Setup

Keycloak has ability  to be deployed on mysql. Basically, keycloak has default database called H2. To change its default database from H2 to mysql its quite simple.

1. Prepare mysql database for mysql.

Create database keycloak.
Create user keycloak with password keycloak.

2. JDBC Setup

Add mysql-connector-java

Kecloak modules mysql driver folder structure

Add module.xml as follow:
<?xml version="1.0" ?>
<module xmlns="urn:jboss:module:1.3" name="com.mysql">
 <resources>
  <resource-root path="mysql-connector-java-5.1.42-bin.jar" />
 </resources>
 <dependencies>
  <module name="javax.api"/>
  <module name="javax.transaction.api"/>
 </dependencies>
</module>

3. Datasource setup

KEYCLOAK_HOME/standalone/configuration/standalone.xml.

<subsystem xmlns="urn:jboss:domain:datasources:4.0">
            <datasources>
                <datasource jndi-name="java:jboss/datasources/ExampleDS" pool-name="ExampleDS" enabled="true" use-java-context="true">
                    <connection-url>jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE</connection-url>
                    <driver>h2</driver>
                    <security>
                        <user-name>sa</user-name>
                        <password>sa</password>
                    </security>
                </datasource>
              <datasource jndi-name="java:/jboss/datasources/KeycloakDS" pool-name="KeycloakDS" enabled="true">
                  <connection-url>jdbc:mysql://localhost:3306/keycloak?useSSL=false&amp;characterEncoding=UTF-8</connection-url>
                  <driver>mysql</driver>
                  <pool>
                      <min-pool-size>5</min-pool-size>
                      <max-pool-size>15</max-pool-size>
                  </pool>
                  <security>
                      <user-name>keycloak</user-name>
                      <password>keycloak</password>
                  </security>
                  <validation>
                      <valid-connection-checker class-name="org.jboss.jca.adapters.jdbc.extensions.mysql.MySQLValidConnectionChecker"/>
                      <validate-on-match>true</validate-on-match>
                      <exception-sorter class-name="org.jboss.jca.adapters.jdbc.extensions.mysql.MySQLExceptionSorter"/>
                  </validation>
              </datasource>
              <drivers>
                    <driver name="h2" module="com.h2database.h2">
                        <xa-datasource-class>org.h2.jdbcx.JdbcDataSource</xa-datasource-class>
                    </driver>
                  <driver name="mysql" module="com.mysql">
                      <driver-class>com.mysql.jdbc.Driver</driver-class>
                  </driver>
              </drivers>
          </datasources>
        </subsystem>
4. Start Keycloak (run ./standalone.sh or ./standalone.bat on KEYCLOAK_HOME/bin)

No comments:

Post a Comment