Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring doesn't see @Transactional when global-method-security namespace is added

I created a service responsible for contact with database through dao. I used @Transactional annotation to handle transactions.

@Service("aclService")
public class HibernateAclServiceImpl implements HibernateAclService{

private final Log logger = LogFactory.getLog(HibernateAclServiceImpl.class);
@Autowired
private AclObjectIdentityDao objectIdentityDao ;
private PermissionFactory permissionFactory = new DefaultPermissionFactory();
@Autowired
private AclCache aclCache;
@Autowired
private PermissionGrantingStrategy grantingStrategy;
@Autowired
private AclAuthorizationStrategy aclAuthorizationStrategy;

private final Field fieldAces = FieldUtils.getField(AclImpl.class, "aces");

@Override
@Transactional
public List<ObjectIdentity> findChildren(ObjectIdentity parentIdentity) {
    AclObjectIdentity aclObjectIdentity = objectIdentityDao
            .get((Long) parentIdentity.getIdentifier());
    List<ObjectIdentity> list = new ArrayList<ObjectIdentity>(
            aclObjectIdentity.getChildren().size());
    for (AclObjectIdentity aoid : aclObjectIdentity.getChildren()) {
        final ObjectIdentity oid = new ObjectIdentityImpl(aoid.getObjectClass().getClazz());
        list.add(oid);
    }
    return list;
}

@Override
@Transactional
public Acl readAclById(ObjectIdentity object) throws NotFoundException {
    final Map<ObjectIdentity, Acl> objects = readAclsById(Arrays.asList(object), null);
    return objects.get(object);
}

@Override
@Transactional
public Acl readAclById(ObjectIdentity object, List<Sid> sids)
        throws NotFoundException {
    Map<ObjectIdentity, Acl> objects = readAclsById(Arrays.asList(object), sids);
    return objects.get(object);
}


@Override
@Transactional
public Map<ObjectIdentity, Acl> readAclsById(List<ObjectIdentity> objects)
        throws NotFoundException {
    return readAclsById(objects, null);
}

@Override
public Map<ObjectIdentity, Acl> readAclsById(List<ObjectIdentity> objects,
        List<Sid> sids) throws NotFoundException {
    Map<ObjectIdentity, Acl> result = new HashMap<ObjectIdentity, Acl>();
    Set<Long> objectsToLoad = new HashSet<Long>();

    for (int i = 0; i < objects.size(); i++) {
        final ObjectIdentity oid = objects.get(i);
        boolean aclFound = false;

        if (result.containsKey(oid)) {
            aclFound = true;
        }

        if (!aclFound) {
            Acl acl = aclCache.getFromCache(oid);

            if (acl != null) {
                if (acl.isSidLoaded(sids)) {
                    result.put(acl.getObjectIdentity(), acl);
                    aclFound = true;
                } else {
                    throw new IllegalStateException(
                            "Error: SID-filtered element detected when implementation does not perform SID filtering "
                                    + "- have you added something to the cache manually?");
                }
            }
        }
        if (!aclFound) {
            objectsToLoad.add((Long) oid.getIdentifier());
        }
    }

    if (objectsToLoad.size() > 0) {
        lookupAcl(result, objectsToLoad);
    }
    return result;
}
public void lookupAcl(Map<ObjectIdentity, Acl> map, Set<Long> objects){
    final List<AclObjectIdentity> aoids = objectIdentityDao.getList(objects);
    final Map<Long, Long> parents = new HashMap<Long, Long>();
    for(AclObjectIdentity aoid : aoids){
        if(aoid.isEntriesInheriting()){
            parents.put(aoid.getId(), aoid.getParent().getId());
        }
    }
    if(parents.size() > 0){
        lookupAcl(map, (Set<Long>)parents.values());
    }
    for(AclObjectIdentity aoid : aoids){
        if(map.containsKey(aoid.getId()))
            continue;
        final Acl parentAcl = map.get(parents.get(aoid.getId()));
        final Acl acl = new AclImpl(new ObjectIdentityImpl(aoid.getObjectClass().getClazz(), aoid.getId()), aoid.getId(), aclAuthorizationStrategy, grantingStrategy, parentAcl, null, aoid.isEntriesInheriting(), new PrincipalSid(aoid.getOwnerSid().getSid()));



        List<AccessControlEntryImpl> aces = new ArrayList<AccessControlEntryImpl>(aoid.getAclEntries().size());
        for(AclEntry aclEntry : aoid.getAclEntries()){
            final Permission permission = permissionFactory.buildFromMask(aclEntry.getMask());
            aces.add(new AccessControlEntryImpl(aclEntry.getId(), acl, new PrincipalSid(aclEntry.getSid().getSid()), permission, aclEntry.isGranting(), aclEntry.isAuditSuccess(), aclEntry.isAuditFailure()));
        }
        setAces((AclImpl) acl, aces);
        aclCache.putInCache((AclImpl) acl);
    }
}

private void setAces(AclImpl acl, List<AccessControlEntryImpl> aces) {
    try {
        fieldAces.set(acl, aces);
    } catch (IllegalAccessException e) {
        throw new IllegalStateException("Could not set AclImpl entries", e);
    }
}

}

Here is a part of my 'app-context.xml' file

<security:global-method-security  pre-post-annotations="enabled">
    <security:expression-handler ref="expressionHandler" />
</security:global-method-security>
<bean id="expressionHandler"
    class="org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler">
    <property name="permissionEvaluator" ref="permissionEvaluator" />
    <property name="roleHierarchy" ref="roleHierarchy" />
</bean>

<bean class="org.springframework.security.acls.AclPermissionEvaluator"
    id="permissionEvaluator">
    <constructor-arg ref="aclService" />
</bean>

Now when I call service's function eg. from controller it throws an error org.hibernate.HibernateException: No Session found for current thread. But everything works great(no problem with transactions) when I comment

<security:global-method-security pre-post-annotations="enabled"> <security:expression-handler ref="expressionHandler" /> </security:global-method-security>

I checked everything, and I narrowed problematic code to the above piece. Have anyone any idea why this is happening?

like image 302
user1137146 Avatar asked Feb 20 '23 01:02

user1137146


1 Answers

I'm not sure how global-method-security is implemented under the covers, but there is a little known side-effect of BeanPostProcessors - any bean referenced directly by a BeanPostProcessor, or referenced by something that that BPP references, are not eligible for AOP auto-proxying:

BeanPostProcessors and AOP auto-proxying

Classes that implement the BeanPostProcessor interface are special and are treated differently by the container. All BeanPostProcessors and beans that they reference directly are instantiated on startup, as part of the special startup phase of the ApplicationContext. Next, all BeanPostProcessors are registered in a sorted fashion and applied to all further beans in the container. Because AOP auto-proxying is implemented as a BeanPostProcessor itself, neither BeanPostProcessors nor the beans they reference directly are eligible for auto-proxying, and thus do not have aspects woven into them.

For any such bean, you should see an informational log message: “Bean foo is not eligible for getting processed by all BeanPostProcessor interfaces (for example: not eligible for auto-proxying)”.

(source)

This means that if you have @Transactional in a bean that is loaded in reference to a BeanPostProcessor, that annotation is effectively ignored.

The solution generally would be that if you need transactional behavior in a bean that has to be loaded in reference to a BeanPostProcessor, you would need to use non-AOP transaction definitions - i.e. use TransactionTemplate.

You can turn up the logging on org.springframework loggers to DEBUG and verify if this message is being output for your aclService bean.

like image 172
matt b Avatar answered Feb 21 '23 13:02

matt b