持久性提供者密码困境

Dav*_*vis 3 java security hibernate jpa jdbc

背景

普通的旧式 Java 应用程序,没有附加 Web 服务器(甚至没有JBoss),正在使用 JPA 来查询数据库。

问题

JDBC 密码暴露在persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
  <persistence-unit name="PU" transaction-type="RESOURCE_LOCAL">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <properties>
      <property name="javax.persistence.jdbc.url" value="jdbc:postgresql:DATABASE"/>
      <property name="javax.persistence.jdbc.user" value="USERNAME"/>
      <property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver"/>
      <property name="javax.persistence.jdbc.password" value="PASSWORD"/>
      <property name="hibernate.cache.provider_class" value="org.hibernate.cache.NoCacheProvider"/>
      <property name="hibernate.hbm2ddl.auto" value="validate"/>
    </properties>
  </persistence-unit>
</persistence>
Run Code Online (Sandbox Code Playgroud)

主意

可以实例化JNDI 子上下文以在应用程序的方法中设置密码main。这可能允许使用 JTA 数据源:

<persistence xmlns="http://java.sun.com/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
             version="2.0">
  <persistence-unit name="PU" transaction-type="RESOURCE_LOCAL">
      <provider>org.hibernate.ejb.HibernatePersistence</provider>
      <jta-data-source>java:/DefaultDS</jta-data-source>
      <properties>
         <property name="hibernate.hbm2ddl.auto" value="create-drop"/>
      </properties>
   </persistence-unit>
</persistence>
Run Code Online (Sandbox Code Playgroud)

问题

如何将密码外部化,使其不再存在于内部persistence.xml

注意:persistence.xml存储在公共存储库中,因此如果密码没有尖叫“请破解我”,那就太好了。相反,JDBC 连接信息应该位于不会签入存储库的文件中。

Dav*_*vis 8

可以通过在实例化时覆盖属性来外部化密码EntityManagerFactory

  private EntityManagerFactory getEntityManagerFactory() {
    return Persistence.createEntityManagerFactory( getPersistenceUnitName(),
      getProperties() );
  }

  private Map getProperties() {
    Map result = new HashMap();

    // Read the properties from a file instead of hard-coding it here.
    // Or pass the password in from the command-line.
    result.put( "javax.persistence.jdbc.password", "PASSWORD" );

    return result;
  }
Run Code Online (Sandbox Code Playgroud)