Saturday, 7 November 2009

Create a default access rule for URLs using Spring Security

Using Spring Security, you can specify access rules for URLs in a declarative manner in a central configuration file. However, it's easy to forget a controller or two, which could have tragic, or at least embarassing, consequences!

One way to avoid that is to create a catch-all rule that will ensure that all URLs are secured. This will be fired if you access a forgotten URL, both prompting you to fix but also preventing anyone exploiting the mistake.

The key to it is realising that the first matching rule from the top is applied to each URL - therefore, defining a catch-all at the bottom will ensure that any unmatched URL is matched by the catch all. The pattern matching is based on Ant patterns, so /** will do the trick.

This is demonsrated below.


Note that the login and logout URLs have been set to ROLE_ANONYMOUS. Otherwise, attempts to access them will result in an infinite loop as the catch all will fire. ROLE_ANONYMOUS is the default role given to all unauthenticated requests by Spring Security - if you have overridden it, use the overridden name instead.

1 comment:

  1. Actually, I'm not so sure creating a global catch all is such a good idea in all circumstances. It creates confusion when people access pages that just don't exist, as the access denied page will show instead of a 404 page. However, it can still be useful to set access rules for an entire directory or set of controllers.