Saturday, February 25, 2012

Creating a Custom Regex Spring Security 3.1 Expression

Summary: What classes to extend in order to make a custom spEL expression for validating with Spring Security 3.1

The other day I found that I would like a way to authorize a user based on a wild card or, better yet, a regex expression, something like:

After much looking around I came up with the following.

First we tell Spring to look at our expression handler for method and web authorization.

Then we create our expression handler to return our custom security root.

And we define our custom security root with our new expression method. Also note the hasIpAddress method. This is there to replace the WebSecurityExpressionRoot so that we can use our new expression on JSPs with spring security's tag.


And we create a custom web security expression handler that returns our custom security root. Again this allows us to use our custom expression method in JSPs, or in URLs if you really wanted.


  1. where are you configuring the bean webSecurityExpressionHandler for use?
    I see only the definition of the bean, but can't see which other bean is using it

    1. Great question! The webSecurityExpressionHandler is what is used on JSPs in the spring security taglib and also if we want to use it to check URLs. It's not referenced anywhere because Spring uses it behind the scenes so we don't need to.

  2. Hi,

    Can you help me, please?

    The method createSecurityExpressionRoot CustomMethodSecurityExpressionHandler class does not work in Spring Security 3.1.1, because its return is MethodSecurityExpressionOperations.

    Thank you.

    1. Hey Jefferson,

      Thanks for pointing out the new changes in 3.1.1. It seems like the MethodSecurityExpressionOperations is similar to SecurityExpressionRoot, but it will take some searching to see how it works in that version. I'll let you know if I come across anything.