Spring Security - Expressions



Spring Security comes with an excellent feature to apply fine-grained control and logic based security layer to application areas. Spring Security employees SpEL, Spring Expression Language to evaluate if the user accessing the resource has required clearance or not. For example instead of checking a user role, we can check if −

  • User is the owner of particular object.

  • Is the IP address of the user within our office network?

Areas of Application

Spring Security Expressions are commonly used in following areas.

  • Method Level − Using @PreAuthorize or @PostAuthorize on controller/service methods, we can control access to methods easily.

  • Application Level − Using SecurityFilterChain, we can use expression using requestMatchers().access() method to restrict access to certain pages matched by expressions.

  • Using TemplatesThymeleaf provides expression capabilities to render tags based on conditions. Similarly in JSP pages we can show/hide buttons to restrict access to certain functionalities.

Expression Vocabulary

Spring Security provides many built-in expressions which are commonly used and cover most of the cases. Following table lists the useful builtin expressions.

Sr. No. Sr. No. Expression Description
1 hasRole('ADMIN') If User is having the given role then hasRole() method returns true otherwise false. Roles are generally prefixed with ROLE_.
2 hasAuthority('READ_PRIVILEGE') If User is having the required previlege then hasAuthority() method returns true otherwise false.
3 hasAnyRole('USER','ADMIN') hasAnyRole() method is used to check if user is having any one of the passed roles.
4 permitAll() For public Urls, permitAll() method is used. It always returns true.
5 denyAll() For hotlised or blocked Urls, denyAll() method is used. It always returns false.
6 isAnonymous() To check if user is not logged in, isAnonymous() method is used. It returns true if user is not logged in.
7 isAuthenticated() To check if user is logged in, isAuthenticated() method is used. It returns true if user is logged in as opposite to isAnonymous() method.
8 principal principal object represents the current user object.

Combinations and Paraemeters

Spring Security Expressions can be combined or can access the parameter passed making it extremely configurable and powerful.

Using Logical Operators

We can use and, or and !(not) operators within an expression to create a complex logic as shown below −

@PreAuthorize("hasRole('USER') and hasRole('EDITOR')")

Accessing Parameters

A method parameter can be accessed in spring expression using # symbol. For if want to verify if the contact information is of the logged-in user to ensure object level sanity.

PreAuthorize("#contact.name == authentication.name")
public void updateDetails(Contact contact) {
    // run the code if contact is of logged-in user only
}

Useful Objects

Spring Security expression provides following objects to get useful information about logged-in user or its operations −

  • principal − Represents UserDetails object

  • autentication − Represents Authentical Object avaiable in SecurityContext object.

  • returnObject − We can utilize returnObject available in @PostAuthorize annotated method to inspect the response before being sent to the user.

Using Custom Beans In Expressions

We can use a custom bean as well within spring security expression. For example, consider a SecurityService Bean

@Component
SecurityService {
   boolean canAccess(Principal, projectId){
      // returns true if user can access the project  
   }
}

We can use the securityService bean and its method within an expression as shown below −

@PreAuthorize("@securityService.canAccess(principal, #projectId)")
Advertisements