【问题标题】:Spring Security PermissionEvaluator: how to implement hasPermission method with object ID?Spring Security PermissionEvaluator:如何使用对象 ID 实现 hasPermission 方法?
【发布时间】:2020-08-03 05:35:49
【问题描述】:

Spring 的 Security "hasPermission" 方法有一个实现,它(据我所知)用于传递类名 (targetType) 和对象 ID (Serializable )。

那么您能否解释一下(至少在一般情况下)如何正确地执行此操作? 我搜索了传递对象 ID 的示例,但没有发现任何(即使在 Spring 的文档中)。

在我的情况下,我想检查用户对我的某些课程的DELETE 权限(例如,“目标”)。所有这些类都有通用的方法和字段,所以我可以有通用的逻辑来检查 PermissionEvaluator 中的权限。

为此,我打算将对象的 ID 和对象的类名传递给 PermissionEvaluator 并在此处进行检查,如下所示:

@PreAuthorize("hasPermission(#id, 'Goal','DELETE')")

在不涉及实现之前听起来不错,因为我真的不明白如何在权限评估器中通过类名和 Id 获取对象的实例。

@Component
public class CustomPermissionEvaluator implements PermissionEvaluator 

 @Override
    public boolean hasPermission(Authentication authentication, Serializable serializable, String targetType,
                                 Object permission) {

是的,我可以通过Class.forName(targetType) 实例化对象,但是我怎样才能通过Id (serializable) 从适当的存储库中获取它的实例呢? (我对每个对象都有不同的存储库)。 @Autowiring 我所有的 30 个存储库都太疯狂了。

【问题讨论】:

    标签: java spring spring-boot spring-security spring-data-jpa


    【解决方案1】:

    实现了我的服务,它接受对象 ID 和对象类型,然后发回对象,我稍后可以将其拆箱。我使用了动态 HQL,因此不需要在 30 多个 JPA 存储库中自动装配(我的错,我一开始就错过了这种可能性)。

    
        @PersistenceContext
        EntityManager entityManager;
    
        static String entityClassPath="com.platform.entity.";
    
        public Object getEntity(String className, Long id) {
    
            String classToQuery = capitalize(className);
    
            /* Check if Entity class exists to decide whether to query DB or not */
            try {
                Class cls = Class.forName(entityClassPath + className);
            } catch (Exception e) {
                return null;
            }
    
            /* Query DB if Entity class exist */
            Query query;
            try {
                query = entityManager.createQuery("SELECT Q FROM " + classToQuery + " Q WHERE Q.id=?1");
                query.setParameter(1, id);
                return query.getSingleResult();
            } catch (Exception e) {
                    e.printStackTrace();
                    return null;
            }
        }
    
    

    【讨论】:

      猜你喜欢
      • 2013-06-25
      • 2012-01-02
      • 2020-09-24
      • 2018-02-03
      • 2015-09-11
      • 2017-10-30
      • 1970-01-01
      • 2018-06-30
      • 2019-02-05
      相关资源
      最近更新 更多