Friday, August 8, 2014

JDBC data sources using blueprint and passwords encrypted

When using blueprint framework for OSGi for configuring JDBC datasources, it is good to store database passwords in encrypted format for security (compliance ?) reasons. Here is a sample blueprint XML configuration for deploying JDBC data sources with blueprint framework with passwords stored in a properties file in encrypted format. In order to achieve this, one need Aries blueprint extension to source the database access credentials from a properties file into the blueprint container context and for encryption need Jasypt . Once the database URL and access credentials are available and encryption algorithm is configured we can configure the JDBC datasource using property place holders. Following is a sample blueprint XML file used for configuring a postgresql database in Apache Karaf which is light weight OSGi based runtime.
<?xml version="1.0" encoding="UTF-8"?>
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"
  xmlns:ext="http://aries.apache.org/blueprint/xmlns/blueprint-ext/v1.0.0"
  xmlns:enc="http://karaf.apache.org/xmlns/jasypt/v1.0.0">

  <ext:property-placeholder>
    <ext:default-properties>
  <ext:property name="db.url" value="localhost:5432/db1" />
  <ext:property name="db.user" value="admin" />
  <ext:property name="db.password" value="" />
 </ext:default-properties>
    <ext:location>file:etc/db.properties</ext:location>
  </ext:property-placeholder>

  <enc:property-placeholder>
    <enc:encryptor class="org.jasypt.encryption.pbe.StandardPBEStringEncryptor">
      <property name="config">
        <bean class="org.jasypt.encryption.pbe.config.EnvironmentStringPBEConfig">
          <property name="algorithm" value="PBEWithMD5AndDES" />
          <property name="passwordEnvName" value="DB_PWD" />
        </bean>
      </property>
    </enc:encryptor>
  </enc:property-placeholder>

   <bean id="dbds" class="org.postgresql.ds.PGSimpleDataSource" >
      <property name="serverName" value="${db.url}"/>
      <property name="user" value="${db.user}"/>
      <property name="password" value="${db.password}"/>
  </bean>

  <service interface="javax.sql.DataSource" ref="dbds">
    <service-properties>
            <entry key="osgi.jndi.service.name" value="jdbc/dbds"/>
    </service-properties>
  </service>
</blueprint>

The blueprint XML file above expects the db.properties file to be available $KARAF_HOME/etc directory. Also environment variable DB_PWD should be set in the environment which will have the password for encryption. Sample db.properties is as following.
#Database properties
db.url=localhost:5432/db1
db.user=dbuserid
db.password=ENC(XYZ6b7Wwq9-+w4Hf9YnQg==)

Note that Jasypt expects the encrypted text in the properties file to be enclosed in ENC()