Method security
An annotation on a bean method says who may call it. The check runs before (or after) every call, whatever the caller is: a controller, a scheduled job, a Flutter widget. A call that is not allowed fails with AccessDeniedException, and the method does not run.
Why
Access rules checked by hand (if (!user.isAdmin) throw ...) end up spread over the code, and one forgotten check opens a method. An annotation puts the rule on the method it protects, where a reader sees it, and the check runs on every path to the method. Because the rule is on the service, not on a URL, it also protects the method when it is called from a job or another service.
Example
@Service()
class OrderService {
OrderService(this.orders);
final OrderRepository orders;
// Admins cancel any order, other users only their own.
@PreAuthorize("hasRole('ADMIN') or #order.owner == principal.username")
Future<void> cancel(Order order) => orders.delete(order);
// Whether the caller may see the order depends on what was loaded.
@PostAuthorize('returnObject.owner == authentication.name')
Future<Order> find(int id) async => (await orders.findById(id))!;
// A plain list of authorities is the whole rule.
@Secured(['ROLE_SUPPORT'])
Future<void> refund(int id) async {}
// Keep only the caller's own orders from the argument.
@PreFilter('filterObject.owner == authentication.name')
Future<void> archive(List<Order> orders) async {}
// Each user gets only their own orders out of the list.
@PostFilter('filterObject.owner == authentication.name')
Future<List<Order>> all() => orders.findAll();
}
The annotations
| Annotation | What it does |
|---|---|
@PreAuthorize(expression) |
Runs the method only when the expression is true. |
@PostAuthorize(expression) |
Hands the result (returnObject) to the caller only when the expression is true. The method has already run: use it for reads, not changes. |
@Secured([...]) |
Runs the method only when the user has one of the listed authorities, written in full (ROLE_ADMIN). |
@PreFilter(expression, filterTarget:) |
Removes from a collection argument the elements (filterObject) for which the expression is false. With several collection parameters, filterTarget names one. |
@PostFilter(expression) |
Removes from the returned List, Set or Map the elements for which the expression is false. Any other result type fails the call. |
On a class, an annotation applies to every method without one of its own (not to getters and setters). A const class that extends PreAuthorize works as a fixed composed annotation:
class AdminOnly extends PreAuthorize {
const AdminOnly() : super("hasRole('ADMIN')");
}
What a call can end in
| Situation | Result |
|---|---|
| No authentication in the security context at all | AuthenticationCredentialsNotFoundException, before any expression runs |
| The expression says no | AccessDeniedException |
The expression fails or does not give a bool |
ArgumentError, and the method does not run |
A synchronous method throws; an async method returns a failed Future, and with @PreAuthorize its body never runs. This package knows nothing of HTTP: in a web application, spring_boot_starter_security turns these exceptions into 401 and 403 answers.
Expressions
The expressions are SpEL, as in Spring:
| In the expression | Is |
|---|---|
hasRole('ADMIN'), hasAnyRole('A', 'B') |
The user has ROLE_ADMIN / one of the roles; a RoleHierarchy bean applies. |
hasAuthority('SCOPE_read'), hasAnyAuthority(...) |
The user has the authority, written in full. |
isAuthenticated(), isFullyAuthenticated(), isAnonymous() |
How the user logged in. |
permitAll, denyAll |
Always / never. |
principal, authentication |
The user (principal.username), the Authentication (authentication.name). |
#order, #p0, #a0 |
The arguments, by name and by position. |
returnObject |
The result (@PostAuthorize). |
filterObject |
The element (@PreFilter, @PostFilter). |
hasPermission(#order, 'cancel'), hasPermission(#id, 'Order', 'cancel') |
Asks the PermissionEvaluator bean; denies when there is none. |
@shop.isOpen() |
A bean, whose class must be @Introspected. |
- Classes of the bean's own package used by the method (
Orderabove) are readable in expressions without@Introspected. - The password of a
Userand the credentials of anAuthenticationare never readable. hasRoleadds the prefixROLE_. For authorities named without it (plainADMINfrom a directory), declare aGrantedAuthorityDefaults('')bean.
@Bean()
GrantedAuthorityDefaults authorityDefaults() => const GrantedAuthorityDefaults('');
Role hierarchies
A RoleHierarchy bean makes a role include others in the expressions (hasRole, hasAuthority and their Any forms).
@Bean()
RoleHierarchy roleHierarchy() => RoleHierarchyImpl.fromHierarchy('''
ROLE_ADMIN > ROLE_STAFF
ROLE_STAFF > ROLE_USER
''');
One A > B or A > B > C rule per line, with full authority names. The rules chain: an admin is also a user. A line that is not a rule, or a cycle, is an ArgumentError.
Permission evaluators
For rules that depend on the object (may this user edit this document?), implement PermissionEvaluator and declare it as a bean:
@Component()
class OrderPermissions implements PermissionEvaluator {
@override
bool hasPermission(Authentication authentication, Object? target, Object permission) =>
target is Order && permission == 'cancel' && target.owner == authentication.name;
@override
bool hasPermissionById(Authentication authentication, Object? targetId, String targetType, Object permission) =>
false; // load the object by id and decide
}
Without such a bean, hasPermission always denies.
How the checks run
- Through the bean's proxy, as in Spring: a call from inside the bean (
this.cancel(...)) is not checked. The generator writes the proxies, so the application needsspring_core_dart_generator. - Always on. Spring needs
@EnableMethodSecurity; here the dependency is enough. A bean with such annotations that cannot be proxied (afinalclass, for example) fails the startup instead of running unchecked. - Parsed at startup. A typo in an expression stops the application.
- Before every other advice.
@Cacheable,@Validatedand the application's aspects run only for an authorized call, so a cached result is never returned to a caller who may not call the method.
In Spring (Java)
@EnableMethodSecurity(securedEnabled = true)
@Configuration
class MethodSecurityConfig {}
@PreAuthorize("hasRole('ADMIN') or #order.owner == principal.username")
public void cancel(Order order) { ... }
The annotations and expressions are Spring's. Not here yet: JSR-250 (@RolesAllowed), annotation templates with parameters, @AuthorizeReturnObject, @HandleAuthorizationDenied, authorization events and ACL tables.