Writing your spring security expression language annotation — PART 1

Baby Steps to Pro
2 min readDec 9, 2021

--

Spring security expression language is very useful. It helps to secure your service/web methods with one line of code. It supports @PreAuthorize and @Secured. In the coming three posts, I will talk about how to add custom behaviour to the @PreAuthorize annotation.

Part 1 — Customize “hasPermission()” expression
Part 2 — Add new customize method security expression
Part 3 — Override default behaviour of spring security expression (e.g. hasRole() , permitAll() …)

In this post, I will discuss how to add custom rule for permission checking in your application. This is somewhat similar to what describe in Sold Craft’s post. You can reference it for more details.

Step 1: Add configuration in your spring security xml file.

You should first add the DefaultMethodSecurityExpressionHandler. It will instantiate a default MethodSecurityExpressionRoot which provides you all the default security expression (e.g. isAutghenticated(), isAnonymous() ,etc ) .

Besides, you have to add a permsisionEvaluator for that ExpressionHandler. If you are using spring security ACL, you could use AclPermissionEvaluator. In our case, we would create a BasePermissionEvaluator as our permission evaluator. You will see in step 2 that we would define custom rules in this permission evaluator.

Step 2: Create your PermissionEvaluator class
You must define a class that implements the org.springframework.security.access.PermissionEvaluator. You have to override the hasPermission() method and define custom rule in this class.

In my example, the user object contains a HashMap which stored the permissions of the user. I will perform checking the permission String against this Hashmap. This HashMap is populated during login by a filter. This part will not be skipped in this example.

For similicity, I just ignore targetDomainObject parameter in my example. By using the targetDomainObject, you can further define security rules on certain domain object of your application.

Step 3: Example usage
You could simply add your the @PreAuthorize(“hasPermission()”) to secure your method.

In the next part of this series of tutorial, I will further discuss how to add your new custom method to the security expression root.

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