Keycloak如何从协议映射器访问数据库

Keycloak how to access DB from protocol mapper

我使用协议映射器通过自定义数据库中的数据丰富令牌。我应该如何部署驱动程序以在协议映射器中使用?如果我在 /standalone/lib/ext keycloak 文件夹中复制驱动程序,那么当映射器正在执行时,我会收到错误消息

SQL exception occuredjava.sql.SQLException: No suitable driver found for jdbc:oracle:thin:@.......:1521/CASDB

驱动程序应该放在哪里?真的有必要将驱动程序部署为 keycloak 模块吗?

我的协议映射器代码

@Override
protected void setClaim(IDToken token, ProtocolMapperModel mappingModel, UserSessionModel userSession, KeycloakSession keycloakSession, ClientSessionContext clientSessionCtx) {
    String field = mappingModel.getConfig().get(FIELD_NAME);
    String type = mappingModel.getConfig().get(TYPE);

    String value = "Test " + type;

    System.out.println(">>>>>>>>>>>> " + type);

    try {
        DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
        Connection con = DriverManager.getConnection(
                "jdbc:oracle:thin:@....:1521/CASDB",
                "....",
                "....");
        Statement stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT * FROM CUSTOMER where CUSTOMER_ID = .....");

        rs.close();
        stmt.close();
        con.close();
    } catch (SQLException e) {
        System.out.println("SQL exception occured" + e);
    } finally {

    }


    OIDCAttributeMapperHelper.mapClaim(token, mappingModel, value);
}

错误是

12:54:40,579 ERROR [org.keycloak.services.error.KeycloakErrorHandler] (default task-6) Uncaught server error: java.lang.NoClassDefFoundError: oracle/jdbc/driver/OracleDriver
at com.betex.keycloak.mapper.UserAttributeMapper.setClaim(UserAttributeMapper.java:72)
at org.keycloak.protocol.oidc.mappers.AbstractOIDCProtocolMapper.transformUserInfoToken(AbstractOIDCProtocolMapper.java:71)
at org.keycloak.protocol.oidc.TokenManager.lambda$transformUserInfoAccessToken(TokenManager.java:716)
at java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:184)
at java.util.stream.ReferencePipeline.accept(ReferencePipeline.java:175)
at java.util.ArrayList.forEach(ArrayList.java:1257)
at java.util.stream.SortedOps$RefSortingSink.end(SortedOps.java:390)
at java.util.stream.Sink$ChainedReference.end(Sink.java:258)
at java.util.stream.Sink$C

但是如果通过 wildfly 数据源测试连接它工作正常

我找到了在 wildfly 服务器上创建 XADatasource 并通过协议映射器代码中的 JNDI 获取它的解决方案。其中 DatasourceName 是在您的 wildfly 数据源配置中定义的名称

示例代码:

InitialContext initialContext = new InitialContext();
Context context = (Context) initialContext.lookup("java:jboss");
DataSource DATASOURCE = (DataSource) context.lookup("/datasources/DatasourceName");