DAO Methods
Spring Security 3.0 introduced the ability to use Spring EL expressions as an authorization mechanism in addition to the simple use of configuration attributes and access-decision voters which have seen before. Expression-based access control is built on the same architecture but allows complicated boolean logic to be encapsulated in a single expression.
With Spring Security you can use an EL statement to limit accessibility via some property of the method parameter.
@PreAuthorize("#contact.name == authentication.name")
public void doSomething(Contact contact);
Here we are accessing another built-in expression, “authentication”, which is the Authentication stored in the security context.
Another option is to filter the Method’s returned List and only return object that meet ACL criteria.
This is done using the @PostFilter annotation, Spring Security iterates through the returned collection and removes any elements for which the supplied expression is false. The name filterObject refers to the current object in the collection.
@PostFilter("filterObject.owners.email == principal.username or hasRole('ROLE_ADMIN')")
List findAll();
The downside to this is the query to the database will return all the Account objects so the DB performance will be impacted.
Hibernate Filters
Filters are a way to combat this potential Database performance issue.
A filter criteria allows you to define a restriction clause similar to the existing “where” attribute available on the class and various collection elements.
You define a filter with @FilterDef giving it a name and named parameters with @ParamDef. Then you can specify usage of that filter on fields of an Entity to limit the returned values.
So to limit entity access you could have a filter like this -
// Define a filter
@FilterDef(name="restrictToUserIdFilter", parameters={@ParamDef(name="userId", type="String")}
// Add a filter to an Entity
@Filter(
name = "restrictToUserIdFilter",
condition="userId = :currentUserId"
)
// Then you enable the filter on the session you make the Criteria query in
Session session = sessionFactory.getCurrentSession();
Filter filter = session.enableFilter("restrictToUserIdFilter");
filter.setParameter("currentUserId", SecurityContextHolder.getContext().getAuthentication().getPrincipal().getUsername());
List results = session.createQuery("from Employee as e where e.salary > :targetSalary")
.setLong("targetSalary", new Long(1000000))
.list();
This will basically wrap your Hibernate generated SQL in a WHERE clause so that only Employee entities with userId = the logged in user will be shown.

