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.
@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

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.

See also