Spring in Practice

Willie Wheeler's Spring blog

Quick Tip: Avoid Rule Duplication When Using Security:authorize

| Comments

Spring Security features a tag that allows us to show or hide JSP content based on access rules we can define. Here’s an example:

<security:authorize access="hasRole('admin')">
    <a href="/main/admin.html">Admin</a>

This is probably the most common way to use the tag. The problem with this approach, though, is that it leads to rule duplication, because the same hasRole(‘admin’) rule is defined in the security application context.

A better approach is to bind the display of the tag body to the user’s actual access to the URL in question. Suppose for example that we have the following definition in the app context:

<intercept-url pattern="/main/admin.html" method="GET"
    access="hasRole('admin')" />

Then we can simply replace the old JSP tag definition with a new one like this:

<security:authorize url="/main/admin.html" method="GET">
    <a href="/main/admin.html">Admin</a>

Now we’ve successfully eliminated the duplicate rule definition. If we were to decide to change the rule to hasRole(‘administrator’), or to anything else for that matter, we’d be able to do that in a single location.