You may refer to (https://tomcat.apache.org/tomcat-8.0-doc/jndi-datasource-examples-howto.html) for details of how to configure a JDBC data source and use it in a web application, this post is going to talk about how to secure database user name and password in the datasource configuration.
STEP 1 : Download Jasypt
We are going to use jasypt for sensitive data encryption and decryption , you may download command line tool from http://www.jasypt.org.
STEP 2 : Encrypt Your Credentials
After downloading jasypt, extract the zip file anywhere and go into bin folder run below commands :
$ ./encrypt.sh input="your-db-user" password=secret-key
$ ./encrypt.sh input="your-db-password" password=secret-key
$ ./encrypt.sh input="your-db-url" password=secret-key
"secret-key" would be needed for decryption, so you need to keep it safe and in this post we are storing and retrieving the secret key from system enviroment variable.
STEP 3 : Configure Your Datasource
Use encrypted values in step 2 to configure your secured datasource in context.xml as below :
STEP 4 : Create Your Own Datasource Factory
As you can see from step 3 we add an attribute "factory" to "Resource" tag which is going to be used to initialise the datasource in the same time decrypt database connection credentials.
STEP 5 : Build Your Own Datasource Factory into a Jar File
Please refer to https://github.com/junjun-dachi/java-util/tree/master/secured-resources-util for the maven project which contains source code of EncryptedDataSourceFactory.
Build "secured-resources-util" project with maven , system would generate a jar file named "secured-resources-1.0.jar".
STEP 6 : Copy Jar Files to Tomcat
You would need to copy below jar file to ${tomcat_dir}/lib in order to have the code running.
1. jasypt-1.9.2.jar
2. sqljdbc42.jar
3. commons-dbcp-1.4.jar
4. commons-pool-1.5.4.jar
5. secured-resources-1.0.jar
STEP 7 : Datasource Injection
In the application code you may inject the datasource as below:
JOB DONE
No comments:
Post a Comment