Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 39 ยท Authorization and Method Security

SpEL Security Expressions and PermissionEvaluator

Write security expressions with SpEL, use method arguments, returnObject and bean references, and implement a PermissionEvaluator for hasPermission checks on domain objects.

Roles are too coarse for the question that matters most in real applications: may this user act on this particular object? "Editors can edit articles" is a role rule. "Editors can edit their own articles, and only while they are drafts" is a rule about data. Spring Security lets you write such rules next to the method with expressions in SpEL, and, when they get complicated, move the logic into a bean or a PermissionEvaluator.

The real Spring code is read-only here. The runnable examples are a tiny expression evaluator and a permission evaluator written in plain Java, so you can see how a rule string becomes a yes or no.

What SpEL gives you

SpEL (Spring Expression Language) is a small expression language that evaluates against a root object. For method security the root exposes these built-ins:

Name Meaning
authentication The current Authentication (authentication.name)
principal The principal object, often your UserDetails
hasRole('X'), hasAnyRole(...), hasAuthority('x') The checks from roles and authorities
permitAll, denyAll, isAuthenticated() Constants and state checks
#param A method parameter, by its name (needs -parameters, which Spring Boot enables)
returnObject The return value (@PostAuthorize only)
filterObject The current element (@PreFilter, @PostFilter)
@beanName.method(...) A call to any Spring bean
hasPermission(target, 'perm') Delegates to a PermissionEvaluator

Examples:

Java
@PreAuthorize("#id == authentication.principal.id")                       // a user may only read their own record
@PreAuthorize("hasRole('ADMIN') or #order.customerId == principal.id")
@PreAuthorize("@orderPolicy.canCancel(#orderId, authentication)")          // call a bean
@PostAuthorize("returnObject.visibility == 'PUBLIC' or returnObject.ownerId == principal.id")

You can use and, or, not (or !), comparison operators, the safe-navigation operator ?. (#doc?.owner), the ternary operator and method calls on any object in scope.

SpEL is evaluated at run time from a string, so a typo (authenticaton.name) compiles fine and fails when the method is first called. Cover every protected method with a test for both the allowed and the denied case.

A rule evaluator you can run

The stand-in below parses a small subset of the language: or, and, !, parentheses, hasRole('X'), hasAuthority('x'), == between dotted paths and string literals. It is not SpEL, but it follows the same idea: the string is the policy, the context supplies the facts.

Java A tiny security-expression evaluator (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The important property is visible: bob has the EDITOR role but fails, because the second condition compares data (article.author) with the caller. That is the "ownership" check, and it is exactly where role-only checks fail.

When expressions get long: use a bean

A rule with three conditions and a database lookup does not belong in an annotation string. Put it in a bean and call it:

Java
@Component("articlePolicy")
class ArticlePolicy {

    private final ArticleRepository articles;

    ArticlePolicy(ArticleRepository articles) { this.articles = articles; }

    public boolean canEdit(long articleId, Authentication auth) {
        return articles.findById(articleId)
            .map(a -> a.getStatus() == Status.DRAFT && a.getAuthor().equals(auth.getName()))
            .orElse(false);
    }
}

@PreAuthorize("@articlePolicy.canEdit(#id, authentication)")
public Article update(long id, ArticleForm form) { ... }

Plain Java is testable, debuggable and refactorable; the annotation stays one line. This is the recommended style for anything beyond a one-line condition.

PermissionEvaluator: hasPermission(target, 'perm')

hasPermission is the built-in extension point for domain-object security. You supply one bean:

Java
@Component
class DocumentPermissionEvaluator implements PermissionEvaluator {

    @Override
    public boolean hasPermission(Authentication auth, Object target, Object permission) {
        if (target instanceof Document d) {
            return switch (permission.toString()) {
                case "read"  -> d.isPublic() || d.getOwner().equals(auth.getName());
                case "write" -> d.getOwner().equals(auth.getName());
                default      -> false;
            };
        }
        return false;
    }

    @Override
    public boolean hasPermission(Authentication auth, Serializable targetId, String targetType, Object permission) {
        // used when only an id is known: load the object, then reuse the rule above
        return false;
    }
}

Spring Boot picks the bean up for method security automatically (in older setups, register it in a DefaultMethodSecurityExpressionHandler). Then:

Java
@PreAuthorize("hasPermission(#doc, 'write')")
public void save(Document doc) { ... }

@PreAuthorize("hasPermission(#id, 'Document', 'read')")     // id + type variant
public Document load(long id) { ... }

The permission model here (Document objects with read and write) is the same idea as Spring Security ACL, a heavier module with its own tables for per-object permissions. For most applications an evaluator that consults your own domain tables is simpler.

Java A PermissionEvaluator with a read/write policy (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Observe the two defensive defaults: an unknown target type and an unknown permission both return false. Deny by default is the habit that makes an evaluator safe to extend.

Mistakes to avoid

  • Authorizing in the controller only, then reusing the service from a scheduled task or a message listener. Put the rule next to the data access.
  • Trusting client-supplied owner ids. #form.ownerId == principal.id is meaningless if the same form lets the user choose ownerId; compare the stored owner, loaded from the database.
  • @PostAuthorize on writes. The method has already executed and committed its change by the time the check runs; use @PreAuthorize for anything that modifies state.
  • Silent false on null. #doc.owner throws if #doc is null; use #doc?.owner and make the rule fail closed.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which expression refers to a method parameter named article?

    prefixes method parameters in SpEL; @ calls a bean.

  2. 2. Why is @PostAuthorize a poor choice for a method that deletes data?

    Post checks run after the method; side effects are not undone by the exception (unless a transaction rolls them back).
  3. 3. What is the purpose of a PermissionEvaluator?

    It is the hook behind hasPermission, so object-level rules live in one Java class.
  4. 4. How should a PermissionEvaluator respond to a target type it does not know?

    Failing closed makes new types and permission names safe until they are handled explicitly.
  5. 5. What is a good way to keep a complex rule readable?

    Plain Java is testable and refactorable; the annotation stays short.

Summary

  • Security expressions use SpEL with authentication, principal, #param, returnObject and @bean references.
  • Use them for object-level rules such as "only the author may edit"; combine with role checks for admins.
  • Move long rules into a bean, or implement PermissionEvaluator for hasPermission.
  • Deny by default for unknown types and permissions, compare against stored data, and use @PreAuthorize for writes.
  • Test both the allowed and denied case: expression typos fail only at run time.

Next: The AuthorizationManager API