concept @postauthorize annotation in category spring

appears as: @PostAuthorize notation, The @PostAuthorize notation, @PostAuthorize notations
Spring Security in Action

This is an excerpt from Manning's book Spring Security in Action.

To apply the post-authorization rules with Spring Security, we use the @PostAuthorize annotation. The @PostAuthorize annotation is very similar to @PreAuthorize, which we discussed in section 16.2. The annotation receives as value the SpEL defining the authorization rule. We’ll continue with an example in which you’ll learn how to use the @PostAuthorize annotation and define post-authorization rules for a method.

The scenario of our example for which I create a project named ssia-ch16-ex3 defines an object Employee. Our Employee has a name, a list of books, and a list of roles. We associate each Employee to a user of the application. To keep consistent with the other examples of this chapter, we’ll define the same users Emma and Natalie. We want to make sure that the caller of the method gets the details of the employee only if the employee has the role “reader”. Because we don’t know the roles associated with the employee record until we retrieve the record, we need to apply the authorization rules after the method execution. For this reason, we’ll use the @PostAuthorize annotation.

Usually, we’d probably get the employee details from a database. To keep our example shorter, I’ll just use a Map with a couple of records, which we’ll consider our data source. In listing 16.9, you find the definition of the BookService class. The BookService class also contains the method for which we apply the authorization rules. Observe that the expression we used with the @PostAuthorize annotation refers to the value returned by the method - returnObject. The post-authorization expression can use the value returned by the method, which is available after the method executes.

Listing 16.9 The BookService class defines the authorized method
@Service
public class BookService {
 
  private Map<String, Employee> records =
    Map.of("emma",
           new Employee("Emma Thompson",
               List.of("Karamazov Brothers"),
               List.of("accountant", "reader")),
           "natalie",
           new Employee("Natalie Parker",
               List.of("Beautiful Paris"),
               List.of("researcher"))
        );
 
 
  @PostAuthorize   #A
   ("returnObject.roles.contains('reader')")
  public Employee getBookDetails(String name) {
      return records.get(name);
  }
}

#A The @PostAuthorize annotation defines the expression for post-authorization.