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
- ObjectIdentity: which object is protected, as a class name plus an id, for example
andcom.shop.Document . The ACL never holds the object itself.7 - Sid (security identity): who an entry is about.
is a user name;PrincipalSid is a role or authority such asGrantedAuthoritySid .ROLE_AUDITOR - Permission: what is allowed, as a bit in an integer mask.
defines five.BasePermission - 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.
stores them in four tables.JdbcMutableAclService - AclPermissionEvaluator: connects ACLs to method security, so that
is answered from the tables.@PreAuthorize("hasPermission(#id, 'com.shop.Document', 'write')")
| Permission | Bit | Mask | Name in expressions |
|---|---|---|---|
READ | 0 | 1 | read |
WRITE | 1 | 2 | write |
CREATE | 2 | 4 | create |
DELETE | 3 | 8 | delete |
ADMINISTRATION | 4 | 16 | administration |
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@PreAuthorize
<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:
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));
}
}
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
holds the identities:acl_sid andann withbob , andprincipal = true withROLE_AUDITOR .principal = false holds one row per protected class, andacl_class one row per protected object. Documents 7 and 8 both point to folder 3 as their parent, but only document 7 hasacl_object_identity .entries_inheriting = true holds the rules. Ann has mask 16,acl_entry , on the folder; Bob has mask 1,ADMINISTRATION ; auditors haveREAD on document 8.READ- Document 7 has no entries of its own, so the folder's two entries are the ones checked, marked
. Document 8 does not inherit, so only its own auditor entry counts, and Bob, who can read the folder, cannot read document 8.inherited - The default identity query of
,JdbcMutableAclService , fails on H2 2.x withcall identity() . InFunction "IDENTITY" not found it returned 100, the first generated id.MODE=LEGACY
The identity query is how the service learns the id of a new acl_sidacl_classsetClassIdentityQuerysetSidIdentityQueryselect currval(pg_get_serial_sequence('acl_class', 'id'))acl_sid
Note the costs this layout implies: one acl_object_identityacl_entryacl_entry
How a permission is decided
AclPermissionEvaluatorLookupStrategyPermissionGrantingStrategyDefaultPermissionGrantingStrategy
- 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,
comparesDefaultPermissionGrantingStrategy.isGranted(ace, p) , for granting and denying entries alike. Override that method in a subclass to compare bits instead.ace.getPermission().getMask() == p.getMask() - 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, ADMINISTRATIONREADCumulativePermission
hasPermission: the method security side
Whatever stores the permissions, the annotations look the same: hasPermission(object, permission)hasPermission(id, type, permission)PermissionEvaluator
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);
}
}
}
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 kept documents 1 and 2, the two she has@PostFilter("hasPermission(filterObject, 'read')") grants for. The evaluator received eachREAD object in turn.Document let her edit document 1 and refused document 2, for which she has only@PreAuthorize("hasPermission(#id, 'Document', 'write')") . This form passes an id and a type name, so nothing has to be loaded first.READ has no grants by name, but his authoritycarl hasROLE_AUDITOR on document 3, so the filter kept it. Like an ACL, the evaluator checks the user name and every authority.READ
Swapping this evaluator for AclPermissionEvaluatoracl_classcom.shop.DocumenthasPermission(filterObject, read)readwritecreatedeleteadminreaddeleteadministration@PostFilter
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 JdbcTemplatemain
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
, as in the reference.static - The identity query:
runsJdbcMutableAclService after inserting ancall identity() oracl_class row. The tables program showed that H2 2.x rejects it, so the URL setsacl_sid . On PostgreSQL, set the two queries in the comment instead.MODE=LEGACY - The cache:
wraps any SpringSpringCacheBasedAclCache . ACache 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.ConcurrentMapCache - 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 SharingMutableAclService
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());
}
}
}
}
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
recorded the signed-in user,createAcl , as the owner of all three objects:ann is 100 in everyowner row, andacl_object_identity row 100 isacl_sid .ann- The ids start at 100 because the schema declares
; each id was read back withstart with 100 in LEGACY mode. Thecall identity() rows foracl_sid andbob were created on first use, withROLE_AUDITOR false for the role.principal - Document 7 has parent 100, the folder, and
true; document 8 has the same parent butinheriting false. Only threeinheriting rows exist: two on the folder and the auditor'sacl_entry on document 8.READ called directly, outside thecreateAcl service, failed with "Transaction must be running". The check guards the insert of a new@Transactional row, here foracl_class , because the identity query must run on the same connection as the insert.com.shop.Invoice- Bob, who has only
on the folder, could not grant himselfREAD . The error is aWRITE , not an access-denied exception: the authorization strategy looked for anNotFoundException entry for him and found none.ADMINISTRATION
The first argument of insertAceupdateAcldeleteAcl(document, true)
Checking permissions with AclPermissionEvaluator
With the ACLs in place, the annotations from the hasPermission
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);
}
}
}
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
entry, because document 7 has no entries of its own and inherits. He was denied document 8, which does not inherit.READ kept 7 for him and 8 for@PostFilter , whosecarl authority hasROLE_AUDITOR there. Document 9 has no ACL at all and was dropped for both.READ - Ann could administer document 7 through the inherited mask 16, but was denied
:read(7) did not implyADMINISTRATION .READ - Carl got a grant and then a deny for
on document 8, and could still read it: the grant came first. After the same deny was inserted at position 0, he was denied, althoughREAD still has its grant further down the list. The first entry matching one of his sids andROLE_AUDITOR was now the deny.READ - A deny entry for Bob on document 7 itself blocked him, although the folder still grants him
. Once an object's own entry matches, the parent is not consulted.READ - The combined permission has mask 3, shown by
asgetPattern() andW in the last two of 32 positions. Granting it to Ann still leftR denied, because 3 is not equal to 1.read(7) - Deleting the auditor's entry with plain SQL did not affect the next check:
could still read document 8, because the ACL came from the cache. Only afterdora was she denied. Change ACLs only throughclearCache() , which evicts the cache, or evict it yourself.MutableAclService
ACL or something simpler
| Need | Approach |
|---|---|
| Only the owner may change a record | @PreAuthorize |
| Sharing with named users or teams, a few permission types | A grants table and a PermissionEvaluatorhasPermission |
| Arbitrary per-object grants, deny entries, inheritance, auditing | spring-security-acl |
| Lists of records the user may see | A query that joins the permission table, not @PostFilter |
| Permissions across many services | A 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