Writing your spring security expression language annotation — PART 2

Baby Steps to Pro
1 min readDec 9, 2021

--

We are now going into the second part of the tutorial. In this post, it will show you how to add a new custom expression for @PreAuthorize annotation. For example, I will show how to add a adminOnly() expression language to the security expression root.

Step 1: Define your custom security expression root class
You have to first create a new security expression root class. This class should be extended from the abstract class org.springframework.security.access.expression.SecurityExpressionRoot. You can add your custom

This class is similar to org.springframework.security.access.expression.method.MethodSecurityExpressionRoot but with your new custom method added. As an example, I just add a very simple mehod adminOnly() which check if the user has admin role.

Step 2: Define your custom expression handler class
To add custom security expression method, you cannot use the DefaultMethodSecurityExpressionHandler. You need to define a new expression handler class by extends the DefaultMethodSecurityExpressionHandler.

You have to override the createSecurityExpressionRoot() method to create your custom security expression root class.

Step 3: Register the custom expression handler in XML

Example usage:

Originally published at https://www.borislam.com on December 9, 2021.

--

--

Baby Steps to Pro
Baby Steps to Pro

Written by Baby Steps to Pro

We are technology enthusiasts with more than 15 years of software development experience. Our current focus is framework development and architectural design.

No responses yet