Spring Security ACLs: permissions stored per object

Roles answer "what may this kind of user do?"; ACLs answer "what may this user do to this one record?". Spring Security's ACL module stores those answers in four tables and checks them from @PreAuthorize with hasPermission. This page explains the model and the tables, then runs the full ACL setup: creating ACLs, granting and denying permissions, and checking them with hasPermission.

Contents

What an ACL adds to roles

Roles and URL rules decide by kind: admins may delete documents, users may read them. Many applications need decisions per record instead: Ann may edit document 7 because she created it, Bob may read it because Ann shared it with him, and auditors may read everything in one folder. An access control list (ACL) stores such decisions as data, one list of entries per protected object.

Spring Security's ACL module, spring-security-acl, models this with a few concepts:

  • ObjectIdentity: which object is protected, as a class name plus an id, for example com.shop.Document and 7. The ACL never holds the object itself.
  • Sid (security identity): who an entry is about. PrincipalSid is a user name; GrantedAuthoritySid is a role or authority such as ROLE_AUDITOR.
  • Permission: what is allowed, as a bit in an integer mask. BasePermission defines five.
  • AccessControlEntry (ACE): one rule, "this sid is granted (or denied) this permission".
  • Acl: the ordered entries of one object, its owner, an optional parent ACL, and a flag saying whether entries are inherited from the parent.
  • AclService and MutableAclService: read ACLs, and create or change them. JdbcMutableAclService stores them in four tables.
  • AclPermissionEvaluator: connects ACLs to method security, so that @PreAuthorize("hasPermission(#id, 'com.shop.Document', 'write')") is answered from the tables.
BasePermission masks
PermissionBitMaskName in expressions
READ01read
WRITE12write
CREATE24create
DELETE38delete
ADMINISTRATION416administration

All programs on this page run with Spring Security 7.1.2, the version Spring Boot 4.1 manages, and H2. The first one creates the four ACL tables by hand to show their layout; the later ones wire up the real ACL module, grant permissions through JdbcMutableAclService and check them with @PreAuthorize. They use a plain Spring context, without Spring Boot auto-configuration, because Spring Boot has no auto-configuration for ACLs: in a Boot application you declare the same beans yourself. The dependency:

XML
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-acl</artifactId>
</dependency>

The four ACL tables, with data

An ACL lives in four tables, and their layout explains most of the module's behaviour. This program creates them with the schema from the Spring Security reference, stores a folder with two documents, and queries which entries apply to each document:

Java
import java.util.List;
import java.util.Map;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.jdbc.datasource.SingleConnectionDataSource;

public class AclTables {

    // The schema from the Spring Security reference (appendix "Database Schema", HyperSQL).
    static final String[] SCHEMA = {
        "create table acl_sid(id bigint generated by default as identity(start with 100)"
            + " not null primary key, principal boolean not null,"
            + " sid varchar_ignorecase(100) not null,"
            + " constraint unique_uk_1 unique(sid,principal))",
        "create table acl_class(id bigint generated by default as identity(start with 100)"
            + " not null primary key, class varchar_ignorecase(100) not null,"
            + " constraint unique_uk_2 unique(class))",
        "create table acl_object_identity(id bigint generated by default as identity"
            + "(start with 100) not null primary key, object_id_class bigint not null,"
            + " object_id_identity varchar_ignorecase(36) not null, parent_object bigint,"
            + " owner_sid bigint, entries_inheriting boolean not null,"
            + " constraint unique_uk_3 unique(object_id_class,object_id_identity),"
            + " constraint foreign_fk_1 foreign key(parent_object)"
            + " references acl_object_identity(id),"
            + " constraint foreign_fk_2 foreign key(object_id_class) references acl_class(id),"
            + " constraint foreign_fk_3 foreign key(owner_sid) references acl_sid(id))",
        "create table acl_entry(id bigint generated by default as identity(start with 100)"
            + " not null primary key, acl_object_identity bigint not null,"
            + " ace_order int not null, sid bigint not null, mask integer not null,"
            + " granting boolean not null, audit_success boolean not null,"
            + " audit_failure boolean not null,"
            + " constraint unique_uk_4 unique(acl_object_identity,ace_order),"
            + " constraint foreign_fk_4 foreign key(acl_object_identity)"
            + " references acl_object_identity(id),"
            + " constraint foreign_fk_5 foreign key(sid) references acl_sid(id))",
    };

    static void print(JdbcTemplate jdbc, String title, String sql) {
        System.out.println(title);
        for (Map<String, Object> row : jdbc.queryForList(sql)) {
            System.out.println("  " + row.values());
        }
    }

    public static void main(String[] args) {
        JdbcTemplate jdbc = new JdbcTemplate(
                new DriverManagerDataSource("jdbc:h2:mem:acl;DB_CLOSE_DELAY=-1"));
        for (String ddl : SCHEMA) {
            jdbc.execute(ddl);
        }
        // Security identities: two users and one role.
        jdbc.update("insert into acl_sid(id, principal, sid) values (1, true, 'ann'),"
                + " (2, true, 'bob'), (3, false, 'ROLE_AUDITOR')");
        jdbc.update("insert into acl_class(id, class) values (10, 'com.shop.Folder'),"
                + " (11, 'com.shop.Document')");
        // Folder 3 owned by ann; document 7 inside it inherits; document 8 does not.
        jdbc.update("insert into acl_object_identity values"
                + " (20, 10, '3', null, 1, false),"
                + " (21, 11, '7', 20, 1, true),"
                + " (22, 11, '8', 20, 1, false)");
        // Masks: READ = 1, WRITE = 2, CREATE = 4, DELETE = 8, ADMINISTRATION = 16.
        jdbc.update("insert into acl_entry(acl_object_identity, ace_order, sid, mask,"
                + " granting, audit_success, audit_failure) values"
                + " (20, 0, 1, 16, true, false, false),"   // ann administers the folder
                + " (20, 1, 2, 1, true, false, false),"    // bob may read the folder
                + " (22, 0, 3, 1, true, true, false)");    // auditors may read document 8

        print(jdbc, "Entries, joined to their object and sid:",
                "select c.class, o.object_id_identity as obj, s.sid, e.mask, e.granting"
                + " from acl_entry e join acl_object_identity o on e.acl_object_identity = o.id"
                + " join acl_class c on o.object_id_class = c.id"
                + " join acl_sid s on e.sid = s.id order by o.id, e.ace_order");

        String checked = "select 'own' as origin, s.sid, e.mask"
                + " from acl_object_identity d join acl_entry e on e.acl_object_identity = d.id"
                + " join acl_sid s on s.id = e.sid where d.object_id_identity = ?"
                + " and d.object_id_class = 11"
                + " union all select 'inherited', s.sid, e.mask from acl_object_identity d"
                + " join acl_entry e on e.acl_object_identity = d.parent_object"
                + " join acl_sid s on s.id = e.sid where d.object_id_identity = ?"
                + " and d.object_id_class = 11 and d.entries_inheriting";
        for (String doc : List.of("7", "8")) {
            System.out.println("Entries checked for document " + doc + ": "
                    + jdbc.queryForList(checked, doc, doc).stream()
                            .map(r -> r.get("SID") + " mask " + r.get("MASK")
                                    + " (" + r.get("ORIGIN") + ")").toList());
        }

        System.out.println("Identity query used by JdbcMutableAclService by default:");
        try {
            jdbc.queryForObject("call identity()", Long.class);
        } catch (DataAccessException e) {
            String message = e.getMostSpecificCause().getMessage();
            System.out.println("  H2 2.x: " + message.substring(0, message.indexOf(';')));
        }
        // identity() is per connection, so this uses one connection for every statement
        JdbcTemplate legacy = new JdbcTemplate(
                new SingleConnectionDataSource("jdbc:h2:mem:legacy;MODE=LEGACY", true));
        legacy.execute(SCHEMA[0]);
        legacy.update("insert into acl_sid(principal, sid) values (true, 'ann')");
        System.out.println("  H2 with MODE=LEGACY: call identity() = "
                + legacy.queryForObject("call identity()", Long.class));
    }
}
Output
Entries, joined to their object and sid:
  [com.shop.Folder, 3, ann, 16, true]
  [com.shop.Folder, 3, bob, 1, true]
  [com.shop.Document, 8, ROLE_AUDITOR, 1, true]
Entries checked for document 7: [ann mask 16 (inherited), bob mask 1 (inherited)]
Entries checked for document 8: [ROLE_AUDITOR mask 1 (own)]
Identity query used by JdbcMutableAclService by default:
  H2 2.x: Function "IDENTITY" not found
  H2 with MODE=LEGACY: call identity() = 100
  • acl_sid holds the identities: ann and bob with principal = true, and ROLE_AUDITOR with principal = false.
  • acl_class holds one row per protected class, and acl_object_identity one row per protected object. Documents 7 and 8 both point to folder 3 as their parent, but only document 7 has entries_inheriting = true.
  • acl_entry holds the rules. Ann has mask 16, ADMINISTRATION, on the folder; Bob has mask 1, READ; auditors have READ on document 8.
  • Document 7 has no entries of its own, so the folder's two entries are the ones checked, marked inherited. Document 8 does not inherit, so only its own auditor entry counts, and Bob, who can read the folder, cannot read document 8.
  • The default identity query of JdbcMutableAclService, call identity(), fails on H2 2.x with Function "IDENTITY" not found. In MODE=LEGACY it returned 100, the first generated id.

The identity query is how the service learns the id of a new acl_sid or acl_class row, and it must run on the same connection as the insert, which is why the program uses a single-connection data source for it. The defaults suit HSQLDB. Other databases need setClassIdentityQuery and setSidIdentityQuery; for PostgreSQL the reference gives select currval(pg_get_serial_sequence('acl_class', 'id')) and the same for acl_sid. The reference also has the schema for MySQL, SQL Server, Oracle and PostgreSQL.

Note the costs this layout implies: one acl_object_identity row per protected object, and one acl_entry row per user or role per permission. With a million documents shared with ten users each, acl_entry holds tens of millions of rows.

How a permission is decided

AclPermissionEvaluator loads the object's ACL through a LookupStrategy, collects the caller's sids (their user name and each of their authorities), and asks the ACL's PermissionGrantingStrategy. The Javadoc of DefaultPermissionGrantingStrategy in Spring Security 7 describes the rules:

  • For each permission requested, the sids are tried in order, and the first entry that matches both a sid and the permission decides: grant or deny.
  • An entry matches a permission only when the two masks are equal. In Spring Security 7.1.2, DefaultPermissionGrantingStrategy.isGranted(ace, p) compares ace.getPermission().getMask() == p.getMask(), for granting and denying entries alike. Override that method in a subclass to compare bits instead.
  • Only when no entry matches at all, and the ACL inherits, is the parent ACL consulted, and then its parent, and so on.
  • If nothing matches anywhere, access is denied.

Two consequences surprise people. First, ADMINISTRATION does not imply READ: they are different masks, so Ann's mask 16 on the folder does not let her read document 7. A combined mask built with CumulativePermission does not help either, because mask 3 is not equal to mask 1. Grant each permission as its own entry. Second, order matters, because the first match wins: a deny entry placed after a grant for the same sid and permission has no effect. The checks program below runs each of these cases.

hasPermission: the method security side

Whatever stores the permissions, the annotations look the same: hasPermission(object, permission) or hasPermission(id, type, permission), both answered by the PermissionEvaluator registered with method security. This program plugs in a small evaluator backed by its own table, and calls the methods as a user and as an auditor:

Java
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import javax.sql.DataSource;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler;
import org.springframework.security.access.expression.method.MethodSecurityExpressionHandler;
import org.springframework.security.access.prepost.PostFilter;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authorization.AuthorizationDeniedException;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;

public class HasPermissionDemo {

    record Document(long id, String title) {
    }

    /** Answers hasPermission(...) from a table of grants: who may do what to which object. */
    static class TablePermissionEvaluator implements PermissionEvaluator {
        private final JdbcTemplate jdbc;

        TablePermissionEvaluator(JdbcTemplate jdbc) {
            this.jdbc = jdbc;
        }

        @Override
        public boolean hasPermission(Authentication auth, Object target, Object permission) {
            return target instanceof Document doc
                    && hasPermission(auth, doc.id(), "Document", permission);
        }

        @Override
        public boolean hasPermission(Authentication auth, Serializable id, String type,
                                     Object permission) {
            List<String> sids = new ArrayList<>(AuthorityUtils.authorityListToSet(
                    auth.getAuthorities()));
            sids.add(auth.getName());
            String in = String.join(",", sids.stream().map(s -> "?").toList());
            List<Object> params = new ArrayList<>(List.of(type, id,
                    permission.toString().toUpperCase(Locale.ROOT)));
            params.addAll(sids);
            Integer n = jdbc.queryForObject("SELECT COUNT(*) FROM grants WHERE object_type = ?"
                    + " AND object_id = ? AND permission = ? AND sid IN (" + in + ")",
                    Integer.class, params.toArray());
            return n != null && n > 0;
        }
    }

    static class DocumentService {
        @PostFilter("hasPermission(filterObject, 'read')")
        public List<Document> all() {
            return new ArrayList<>(List.of(new Document(1, "Budget 2026"),
                    new Document(2, "Hiring plan"), new Document(3, "Audit report")));
        }

        @PreAuthorize("hasPermission(#id, 'Document', 'write')")
        public String edit(long id) {
            return "edited document " + id;
        }
    }

    @Configuration
    @EnableMethodSecurity
    static class Config {
        @Bean
        static JdbcTemplate jdbc() {
            DataSource ds = new DriverManagerDataSource("jdbc:h2:mem:grants;DB_CLOSE_DELAY=-1");
            JdbcTemplate jdbc = new JdbcTemplate(ds);
            jdbc.execute("CREATE TABLE grants (sid VARCHAR(40), object_type VARCHAR(40),"
                    + " object_id BIGINT, permission VARCHAR(10))");
            jdbc.update("INSERT INTO grants VALUES ('ann', 'Document', 1, 'READ'),"
                    + " ('ann', 'Document', 1, 'WRITE'), ('ann', 'Document', 2, 'READ'),"
                    + " ('ROLE_AUDITOR', 'Document', 3, 'READ')");
            return jdbc;
        }

        @Bean
        static MethodSecurityExpressionHandler expressionHandler(JdbcTemplate jdbc) {
            DefaultMethodSecurityExpressionHandler handler =
                    new DefaultMethodSecurityExpressionHandler();
            handler.setPermissionEvaluator(new TablePermissionEvaluator(jdbc));
            return handler;
        }

        @Bean
        DocumentService documentService() {
            return new DocumentService();
        }
    }

    static void as(String user, String... authorities) {
        SecurityContextHolder.getContext().setAuthentication(
                UsernamePasswordAuthenticationToken.authenticated(user, null,
                        AuthorityUtils.createAuthorityList(authorities)));
        System.out.println(user + " " + List.of(authorities) + ":");
    }

    static void edit(DocumentService docs, long id) {
        try {
            System.out.println("  edit(" + id + ") -> " + docs.edit(id));
        } catch (AuthorizationDeniedException e) {
            System.out.println("  edit(" + id + ") -> " + e.getMessage());
        }
    }

    public static void main(String[] args) {
        try (var context = new AnnotationConfigApplicationContext(Config.class)) {
            DocumentService docs = context.getBean(DocumentService.class);
            as("ann", "ROLE_USER");
            System.out.println("  all() -> " + docs.all());
            edit(docs, 1);
            edit(docs, 2);
            as("carl", "ROLE_USER", "ROLE_AUDITOR");
            System.out.println("  all() -> " + docs.all());
            edit(docs, 3);
        }
    }
}
Output
ann [ROLE_USER]:
  all() -> [Document[id=1, title=Budget 2026], Document[id=2, title=Hiring plan]]
  edit(1) -> edited document 1
  edit(2) -> Access Denied
carl [ROLE_USER, ROLE_AUDITOR]:
  all() -> [Document[id=3, title=Audit report]]
  edit(3) -> Access Denied
  • For ann, @PostFilter("hasPermission(filterObject, 'read')") kept documents 1 and 2, the two she has READ grants for. The evaluator received each Document object in turn.
  • @PreAuthorize("hasPermission(#id, 'Document', 'write')") let her edit document 1 and refused document 2, for which she has only READ. This form passes an id and a type name, so nothing has to be loaded first.
  • carl has no grants by name, but his authority ROLE_AUDITOR has READ on document 3, so the filter kept it. Like an ACL, the evaluator checks the user name and every authority.

Swapping this evaluator for AclPermissionEvaluator changes nothing in the annotated code apart from the type argument, which for ACLs must be the class name stored in acl_class, such as com.shop.Document. With ACLs, the permission can also be written unquoted, as in the reference's hasPermission(filterObject, read): the expression root has fields read, write, create, delete and admin, holding the strings read to delete and administration. The @PostFilter caveats from the method security page apply here too: every row is loaded first, and then each is checked one by one.

Configuring the ACL module

The ACL module needs six beans wired together, following the configuration in the Spring Security reference. This class adds an H2 data source with the schema from the first program, a transaction manager and a JdbcTemplate. It has no main: the next two programs start a context from it.

Java
import javax.sql.DataSource;
import org.springframework.cache.concurrent.ConcurrentMapCache;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler;
import org.springframework.security.access.expression.method.MethodSecurityExpressionHandler;
import org.springframework.security.acls.AclPermissionEvaluator;
import org.springframework.security.acls.domain.AclAuthorizationStrategy;
import org.springframework.security.acls.domain.AclAuthorizationStrategyImpl;
import org.springframework.security.acls.domain.ConsoleAuditLogger;
import org.springframework.security.acls.domain.DefaultPermissionGrantingStrategy;
import org.springframework.security.acls.domain.SpringCacheBasedAclCache;
import org.springframework.security.acls.jdbc.BasicLookupStrategy;
import org.springframework.security.acls.jdbc.JdbcMutableAclService;
import org.springframework.security.acls.jdbc.LookupStrategy;
import org.springframework.security.acls.model.AclCache;
import org.springframework.security.acls.model.AclService;
import org.springframework.security.acls.model.PermissionGrantingStrategy;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/** The ACL beans, shared by AclGrants and AclChecks. Not a program on its own. */
@Configuration
@EnableMethodSecurity
@EnableTransactionManagement
public class AclConfig {

    @Bean
    static DataSource dataSource() {
        // MODE=LEGACY brings back H2 1.x's identity(), which JdbcMutableAclService calls
        DataSource ds = new DriverManagerDataSource(
                "jdbc:h2:mem:acls;MODE=LEGACY;DB_CLOSE_DELAY=-1");
        JdbcTemplate jdbc = new JdbcTemplate(ds);
        for (String ddl : AclTables.SCHEMA) {
            jdbc.execute(ddl);
        }
        return ds;
    }

    @Bean
    static JdbcTemplate jdbcTemplate(DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }

    @Bean
    static PlatformTransactionManager transactionManager(DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean
    static MethodSecurityExpressionHandler expressionHandler(AclPermissionEvaluator evaluator) {
        DefaultMethodSecurityExpressionHandler handler =
                new DefaultMethodSecurityExpressionHandler();
        handler.setPermissionEvaluator(evaluator);
        return handler;
    }

    @Bean
    static AclPermissionEvaluator aclPermissionEvaluator(AclService aclService) {
        return new AclPermissionEvaluator(aclService);
    }

    @Bean
    static PermissionGrantingStrategy permissionGrantingStrategy() {
        return new DefaultPermissionGrantingStrategy(new ConsoleAuditLogger());
    }

    @Bean
    static AclAuthorizationStrategy aclAuthorizationStrategy() {
        // who may change ownership, auditing and other details of any object's ACL
        return new AclAuthorizationStrategyImpl(new SimpleGrantedAuthority("ROLE_ADMIN"));
    }

    @Bean
    static AclCache aclCache(PermissionGrantingStrategy granting,
                             AclAuthorizationStrategy authorization) {
        return new SpringCacheBasedAclCache(new ConcurrentMapCache("acl"), granting,
                authorization);
    }

    @Bean
    static LookupStrategy lookupStrategy(DataSource dataSource, AclCache cache,
                                         AclAuthorizationStrategy authorization,
                                         PermissionGrantingStrategy granting) {
        return new BasicLookupStrategy(dataSource, cache, authorization, granting);
    }

    @Bean
    static JdbcMutableAclService aclService(DataSource dataSource, LookupStrategy lookup,
                                            AclCache cache) {
        // The defaults, "call identity()", suit HSQLDB and H2 in LEGACY mode. PostgreSQL:
        // setClassIdentityQuery("select currval(pg_get_serial_sequence('acl_class', 'id'))")
        // setSidIdentityQuery("select currval(pg_get_serial_sequence('acl_sid', 'id'))")
        return new JdbcMutableAclService(dataSource, lookup, cache);
    }
}
  • Static bean methods: the expression handler is needed while method security itself is being set up, so it and the beans it depends on are declared static, as in the reference.
  • The identity query: JdbcMutableAclService runs call identity() after inserting an acl_class or acl_sid row. The tables program showed that H2 2.x rejects it, so the URL sets MODE=LEGACY. On PostgreSQL, set the two queries in the comment instead.
  • The cache: SpringCacheBasedAclCache wraps any Spring Cache. A ConcurrentMapCache never expires entries and is local to one server; with several servers, use a shared cache, or ACL changes made on one server are not seen by the others.
  • AclAuthorizationStrategyImpl: takes one authority for all ACL changes, or three for changing ownership, auditing and everything else, in that order. Without that authority, a user may still change an ACL they own, or one on which they hold ADMINISTRATION.

Creating ACLs and granting permissions

Spring Security does not create or delete ACLs when your domain objects are saved or deleted; your service has to. The Sharing service below does it with MutableAclService. The program builds the same folder and documents as the tables section, this time through the API, and prints the rows it produced. It then tries two changes that should fail.

Java
import java.util.Map;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.acls.domain.BasePermission;
import org.springframework.security.acls.domain.GrantedAuthoritySid;
import org.springframework.security.acls.domain.ObjectIdentityImpl;
import org.springframework.security.acls.domain.PrincipalSid;
import org.springframework.security.acls.model.MutableAcl;
import org.springframework.security.acls.model.MutableAclService;
import org.springframework.security.acls.model.NotFoundException;
import org.springframework.security.acls.model.ObjectIdentity;
import org.springframework.security.acls.model.Permission;
import org.springframework.security.acls.model.Sid;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.transaction.annotation.Transactional;

public class AclGrants {
    static final String FOLDER = "com.shop.Folder";
    static final String DOCUMENT = "com.shop.Document";

    /** What an application service does when objects are created and shared. */
    public static class Sharing {
        private final MutableAclService acls;

        public Sharing(MutableAclService acls) {
            this.acls = acls;
        }

        @Transactional
        public void register(String type, long id, String parentType, Long parentId,
                             boolean inheriting) {
            MutableAcl acl = acls.createAcl(new ObjectIdentityImpl(type, id)); // owner: caller
            if (parentId != null) {
                acl.setParent(acls.readAclById(new ObjectIdentityImpl(parentType, parentId)));
            }
            acl.setEntriesInheriting(inheriting);
            acls.updateAcl(acl);
        }

        @Transactional
        public void grant(String type, long id, Sid sid, Permission permission,
                          boolean granting) {
            insert(type, id, -1, sid, permission, granting);
        }

        /** Adds an entry at a position in the list, or at the end for -1. */
        @Transactional
        public void insert(String type, long id, int index, Sid sid, Permission permission,
                           boolean granting) {
            ObjectIdentity object = new ObjectIdentityImpl(type, id);
            MutableAcl acl;
            try {
                acl = (MutableAcl) acls.readAclById(object);
            } catch (NotFoundException e) {
                acl = acls.createAcl(object);
            }
            acl.insertAce(index < 0 ? acl.getEntries().size() : index, permission, sid,
                    granting);
            acls.updateAcl(acl);
        }
    }

    static void as(String user, String... authorities) {
        SecurityContextHolder.getContext().setAuthentication(
                UsernamePasswordAuthenticationToken.authenticated(user, null,
                        AuthorityUtils.createAuthorityList(authorities)));
    }

    /** Folder 3 owned by ann, document 7 inside it inheriting, document 8 not. */
    static void sampleData(ApplicationContext context) {
        Sharing sharing = context.getBean(Sharing.class);
        as("ann", "ROLE_USER");
        sharing.register(FOLDER, 3, null, null, false);
        sharing.grant(FOLDER, 3, new PrincipalSid("ann"), BasePermission.ADMINISTRATION, true);
        sharing.grant(FOLDER, 3, new PrincipalSid("bob"), BasePermission.READ, true);
        sharing.register(DOCUMENT, 7, FOLDER, 3L, true);
        sharing.register(DOCUMENT, 8, FOLDER, 3L, false);
        sharing.grant(DOCUMENT, 8, new GrantedAuthoritySid("ROLE_AUDITOR"),
                BasePermission.READ, true);
    }

    static void print(JdbcTemplate jdbc, String title, String sql) {
        System.out.println(title);
        for (Map<String, Object> row : jdbc.queryForList(sql)) {
            System.out.println("  " + row.values());
        }
    }

    public static void main(String[] args) {
        try (var context = new AnnotationConfigApplicationContext(AclConfig.class,
                Sharing.class)) {
            sampleData(context);
            JdbcTemplate jdbc = context.getBean(JdbcTemplate.class);
            print(jdbc, "acl_sid (id, principal, sid):", "select * from acl_sid order by id");
            print(jdbc, "acl_class (id, class):", "select * from acl_class order by id");
            print(jdbc, "acl_object_identity (id, class, object, parent, owner, inheriting):",
                    "select * from acl_object_identity order by id");
            print(jdbc, "acl_entry (object, order, sid, mask, granting):",
                    "select acl_object_identity, ace_order, sid, mask, granting"
                    + " from acl_entry order by id");

            MutableAclService acls = context.getBean(MutableAclService.class);
            System.out.println("Trying to change ACLs:");
            try {
                acls.createAcl(new ObjectIdentityImpl("com.shop.Invoice", 1));
            } catch (RuntimeException e) {
                System.out.println("  createAcl outside a transaction -> "
                        + e.getClass().getSimpleName() + ": " + e.getMessage());
            }
            as("bob", "ROLE_USER");
            try {
                context.getBean(Sharing.class).grant(FOLDER, 3, new PrincipalSid("bob"),
                        BasePermission.WRITE, true);
            } catch (RuntimeException e) {
                System.out.println("  bob grants himself WRITE on folder 3 -> "
                        + e.getClass().getSimpleName() + ": " + e.getMessage());
            }
        }
    }
}
Output
acl_sid (id, principal, sid):
  [100, true, ann]
  [101, true, bob]
  [102, false, ROLE_AUDITOR]
acl_class (id, class):
  [100, com.shop.Folder]
  [101, com.shop.Document]
acl_object_identity (id, class, object, parent, owner, inheriting):
  [100, 100, 3, null, 100, false]
  [101, 101, 7, 100, 100, true]
  [102, 101, 8, 100, 100, false]
acl_entry (object, order, sid, mask, granting):
  [100, 0, 100, 16, true]
  [100, 1, 101, 1, true]
  [102, 0, 102, 1, true]
Trying to change ACLs:
  createAcl outside a transaction -> IllegalArgumentException: Transaction must be running
  bob grants himself WRITE on folder 3 -> NotFoundException: Unable to locate a matching ACE for passed permissions and SIDs
  • createAcl recorded the signed-in user, ann, as the owner of all three objects: owner is 100 in every acl_object_identity row, and acl_sid row 100 is ann.
  • The ids start at 100 because the schema declares start with 100; each id was read back with call identity() in LEGACY mode. The acl_sid rows for bob and ROLE_AUDITOR were created on first use, with principal false for the role.
  • Document 7 has parent 100, the folder, and inheriting true; document 8 has the same parent but inheriting false. Only three acl_entry rows exist: two on the folder and the auditor's READ on document 8.
  • createAcl called directly, outside the @Transactional service, failed with "Transaction must be running". The check guards the insert of a new acl_class row, here for com.shop.Invoice, because the identity query must run on the same connection as the insert.
  • Bob, who has only READ on the folder, could not grant himself WRITE. The error is a NotFoundException, not an access-denied exception: the authorization strategy looked for an ADMINISTRATION entry for him and found none.

The first argument of insertAce is the position in the list, and the last one says whether the entry grants or denies. updateAcl deletes all the object's entries and inserts them again on every call, so frequent changes to objects with many entries are expensive. When a document is deleted, call deleteAcl(document, true), or its rows are left behind.

Checking permissions with AclPermissionEvaluator

With the ACLs in place, the annotations from the hasPermission section are answered from the tables. This program reuses the configuration and sample data, then checks each rule from the "How a permission is decided" section, adding entries as it goes:

Java
import java.util.ArrayList;
import java.util.List;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.access.prepost.PostFilter;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.acls.domain.BasePermission;
import org.springframework.security.acls.domain.CumulativePermission;
import org.springframework.security.acls.domain.PrincipalSid;
import org.springframework.security.acls.model.AclCache;
import org.springframework.security.authorization.AuthorizationDeniedException;

public class AclChecks {

    public static class Documents {
        @PreAuthorize("hasPermission(#id, 'com.shop.Document', 'read')")
        public String read(long id) {
            return "read";
        }

        @PreAuthorize("hasPermission(#id, 'com.shop.Document', 'administration')")
        public String administer(long id) {
            return "administered";
        }

        @PostFilter("hasPermission(filterObject, 'com.shop.Document', 'read')")
        public List<Long> ids() {
            return new ArrayList<>(List.of(7L, 8L, 9L));
        }
    }

    static void check(String label, Documents docs, String method, long id) {
        String result;
        try {
            result = method.equals("read") ? docs.read(id) : docs.administer(id);
        } catch (AuthorizationDeniedException e) {
            result = e.getMessage();
        }
        System.out.println("  " + label + " " + method + "(" + id + ") -> " + result);
    }

    public static void main(String[] args) {
        try (var context = new AnnotationConfigApplicationContext(AclConfig.class,
                AclGrants.Sharing.class, Documents.class)) {
            AclGrants.sampleData(context);
            AclGrants.Sharing sharing = context.getBean(AclGrants.Sharing.class);
            Documents docs = context.getBean(Documents.class);

            System.out.println("Inheritance:");
            AclGrants.as("bob", "ROLE_USER");
            check("bob", docs, "read", 7);
            check("bob", docs, "read", 8);
            System.out.println("  bob ids() -> " + docs.ids());
            AclGrants.as("carl", "ROLE_USER", "ROLE_AUDITOR");
            check("carl", docs, "read", 8);
            System.out.println("  carl ids() -> " + docs.ids());

            System.out.println("ADMINISTRATION is its own bit:");
            AclGrants.as("ann", "ROLE_USER");
            check("ann", docs, "administer", 7);
            check("ann", docs, "read", 7);

            System.out.println("First matching entry wins:");
            PrincipalSid carl = new PrincipalSid("carl");
            AclGrants.as("ann", "ROLE_USER");
            sharing.grant(AclGrants.DOCUMENT, 8, carl, BasePermission.READ, true);
            sharing.grant(AclGrants.DOCUMENT, 8, carl, BasePermission.READ, false); // deny
            AclGrants.as("carl", "ROLE_USER", "ROLE_AUDITOR");
            check("carl, grant then deny:", docs, "read", 8);
            AclGrants.as("ann", "ROLE_USER");
            sharing.insert(AclGrants.DOCUMENT, 8, 0, carl, BasePermission.READ, false);
            AclGrants.as("carl", "ROLE_USER", "ROLE_AUDITOR");
            check("carl, deny moved first:", docs, "read", 8);
            AclGrants.as("ann", "ROLE_USER");
            sharing.grant(AclGrants.DOCUMENT, 7, new PrincipalSid("bob"),
                    BasePermission.READ, false);
            AclGrants.as("bob", "ROLE_USER");
            check("bob, deny on document 7:", docs, "read", 7);

            System.out.println("A combined mask:");
            AclGrants.as("ann", "ROLE_USER");
            CumulativePermission readWrite = new CumulativePermission()
                    .set(BasePermission.READ).set(BasePermission.WRITE);
            System.out.println("  READ|WRITE = mask " + readWrite.getMask() + ", pattern "
                    + readWrite.getPattern());
            sharing.grant(AclGrants.DOCUMENT, 7, new PrincipalSid("ann"), readWrite, true);
            check("ann", docs, "read", 7);

            System.out.println("Changing the tables behind the cache's back:");
            JdbcTemplate jdbc = context.getBean(JdbcTemplate.class);
            int removed = jdbc.update("delete from acl_entry where sid ="
                    + " (select id from acl_sid where sid = 'ROLE_AUDITOR')");
            System.out.println("  deleted " + removed + " ROLE_AUDITOR entry with SQL");
            AclGrants.as("dora", "ROLE_AUDITOR");
            check("dora", docs, "read", 8);
            context.getBean(AclCache.class).clearCache();
            check("dora, after clearCache():", docs, "read", 8);
        }
    }
}
Output
Inheritance:
  bob read(7) -> read
  bob read(8) -> Access Denied
  bob ids() -> [7]
  carl read(8) -> read
  carl ids() -> [8]
ADMINISTRATION is its own bit:
  ann administer(7) -> administered
  ann read(7) -> Access Denied
First matching entry wins:
  carl, grant then deny: read(8) -> read
  carl, deny moved first: read(8) -> Access Denied
  bob, deny on document 7: read(7) -> Access Denied
A combined mask:
  READ|WRITE = mask 3, pattern ..............................WR
  ann read(7) -> Access Denied
Changing the tables behind the cache's back:
  deleted 1 ROLE_AUDITOR entry with SQL
  dora read(8) -> read
  dora, after clearCache(): read(8) -> Access Denied
  • Bob read document 7 through the folder's READ entry, because document 7 has no entries of its own and inherits. He was denied document 8, which does not inherit. @PostFilter kept 7 for him and 8 for carl, whose ROLE_AUDITOR authority has READ there. Document 9 has no ACL at all and was dropped for both.
  • Ann could administer document 7 through the inherited mask 16, but was denied read(7): ADMINISTRATION did not imply READ.
  • Carl got a grant and then a deny for READ on document 8, and could still read it: the grant came first. After the same deny was inserted at position 0, he was denied, although ROLE_AUDITOR still has its grant further down the list. The first entry matching one of his sids and READ was now the deny.
  • A deny entry for Bob on document 7 itself blocked him, although the folder still grants him READ. Once an object's own entry matches, the parent is not consulted.
  • The combined permission has mask 3, shown by getPattern() as W and R in the last two of 32 positions. Granting it to Ann still left read(7) denied, because 3 is not equal to 1.
  • Deleting the auditor's entry with plain SQL did not affect the next check: dora could still read document 8, because the ACL came from the cache. Only after clearCache() was she denied. Change ACLs only through MutableAclService, which evicts the cache, or evict it yourself.

ACL or something simpler

Ways to implement object-level permissions
NeedApproach
Only the owner may change a record@PreAuthorize with a bean method that compares the owner column, see method security
Sharing with named users or teams, a few permission typesA grants table and a PermissionEvaluator, as in the hasPermission section
Arbitrary per-object grants, deny entries, inheritance, auditingspring-security-acl
Lists of records the user may seeA query that joins the permission table, not @PostFilter
Permissions across many servicesA central authorization service or a relationship-based model such as Google Zanzibar and its open-source descendants, called from a PermissionEvaluator

The ACL module is mature and general, but it is also heavy: four tables, six beans, a cache that must be shared, and no help with listing what a user may see. Many applications need only owners and a simple sharing table, which a PermissionEvaluator of fifty lines handles with the same annotations. Start there, and move to ACLs when deny entries, inheritance or per-entry auditing are real requirements. For the rest of the security setup, see Spring Security in Spring Boot.