我无法找到有关我遇到的此问题的信息。我对在Postgres db上实现行级安全性感兴趣,我正在寻找一种方法,能够通过某种形式的拦截器自动设置postgres会话变量。现在,我知道使用hibernate可以使用@Filter
和@FilterDef
进行行级安全,但是我想在数据库上另外设置策略。
一种非常简单的方法是在每次查询之前执行SQL语句SET variable=value
,尽管我还没有找到任何关于此的信息。
这是在Spring Boot应用程序上使用的,并且每个请求都可以访问variable
的请求特定值。
最佳答案
由于您的应用程序使用spring,因此您可以尝试通过以下几种方法之一来完成此任务:
春季AOP
在这种方法中,您编写了一条建议,要求Spring将其应用于特定方法。如果您的方法使用@Transactional
批注,则可以在事务开始后立即将建议应用于那些建议。
扩展的TransactionManager实施
假设您的交易正在使用JpaTransactionManager
。
public class SecurityPolicyInjectingJpaTransactionManager extends JpaTransactionManager {
@Autowired
private EntityManager entityManager;
// constructors
@Override
protected void prepareSynchronization(DefaultTransactionStatus status, TransactionDefinition definition) {
super.prepareSynchronization(status, definition);
if (status.isNewTransaction()) {
// Use entityManager to execute your database policy param/values
// I would suggest you also register an after-completion callback synchronization
// This after-completion would clear all the policy param/values
// regardless of whether the transaction succeeded or failed
// since this happens just before it gets returned to the connection pool
}
}
}
现在,只需将JPA环境配置为使用自定义
JpaTransactionManager
类。可能还有其他一些,但是我已经探究过这两个。