Close

Spring Security - Expression-Based Access Control with @PreAuthorize

[Last Updated: Sep 11, 2017]

Spring Security provides the ability to use Spring EL expressions as an authorization mechanism. We can use @PreAuthorize annotation and can specify method access-control expression as its attribute.

There are four annotations which support expression attributes to allow pre and post-invocation authorization checks around methods: @PreAuthorize, @PreFilter, @PostAuthorize and @PostFilter.

@PreFilter and @PostFilter annotations support filtering of submitted collection arguments or return values.

Following example shows the use of @PreAuthorize.

Example

We are going to reuse our @Secured annotation example. We just need to replace @Secured with @PreAuthorize annotation in the service class and enabled pre/post annotations in Java config class via prePostEnabled = true .

Service Interface

package com.logicbig.example;

import org.springframework.security.access.prepost.PreAuthorize;

import java.util.List;

public interface ShoppingCartService {
  @PreAuthorize("hasAuthority('ROLE_CUSTOMER')")
  int placeOrder(OrderItem order);

  @PreAuthorize("hasAuthority('ROLE_ADMIN')")
  List<OrderItem> getOrderList();
}

Here is a list of the expressions which can be used with the pre/post annotations.

Java Config class

@Configuration
@EnableWebSecurity
@EnableWebMvc
@ComponentScan
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class AppConfig extends WebSecurityConfigurerAdapter {
    .............
}

To try examples, run embedded tomcat (configured in pom.xml of example project below):

mvn tomcat7:run-war

The output will be same as this example.

Example Project

Dependencies and Technologies Used:

  • spring-security-web 4.2.3.RELEASE: spring-security-web.
  • spring-security-config 4.2.3.RELEASE: spring-security-config.
  • spring-webmvc 4.3.9.RELEASE: Spring Web MVC.
  • javax.servlet-api 3.1.0 Java Servlet API
  • JDK 1.8
  • Maven 3.3.9

Method Security with @PreAuthorize Select All Download
  • method-security-with-pre-authorize-annotation
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • ShoppingCartService.java
          • webapp
            • WEB-INF
              • views

    See Also