java - 持久性提供者密码困境

标签 java hibernate security 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>

想法

也许可以实例化 JNDI subcontext在应用程序的 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>

问题

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

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

最佳答案

密码可以通过 overriding 外部化实例化 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;
  }

关于java - 持久性提供者密码困境,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37914697/

相关文章:

java - 将上下文从 Activity 传递到静态类是否会永远保留该 Activity?内存泄漏?

java - 是否有用于将谓词定义为类似 SQL 的字符串的 Java 库?

java - MySql 左外连接未按预期工作

mysql - 一般意义上的 h2 与 hibernate 和 MySql 之间的区别

java - 生产JVM的安全调试

java - 带有 java.lang.ClassNotFoundException 的 SWT FileDialog

java - Gwt Mockito : @RunWith(GwtMockitoTestRunner. 类)导致异常

java - java持久化中注解映射是如何完成的?

安全性(又名权限)和 Lucene - 如何?应该这样做吗?

c++ - 在 PAM 模块之间传递密码