Spring Security 2.0 has improved support substantially for adding security to your service layer methods. If you are
using Java 5 or greater, then support for JSR-250 security annotations is provided, as well as the framework's native
@Secured
annotation. You can apply security to a single bean, using the intercept-methods
element to decorate the bean declaration, or you can secure multiple beans across the entire service layer using the
AspectJ style pointcuts.
This element is used to enable annotation-based security in your application (by setting the appropriate
attributes on the element), and also to group together security pointcut declarations which will be applied across your
entire application context. You should only declare one <global-method-security>
element.
The following declaration would enable support for both Spring Security's @Secured
, and JSR-250 annotations:
<global-method-security secured-annotations="enabled" jsr250-annotations="enabled"/>
Adding an annotation to a method (on an class or interface) would then limit the access to that method
accordingly. Spring Security's native annotation support defines a set of attributes for the method. These
will be passed to the AccessDecisionManager
for it to make the actual decision.
This example is taken from the tutorial sample, which is a good
starting point if you want to use method security in your application:
public interface BankService { @Secured("IS_AUTHENTICATED_ANONYMOUSLY") public Account readAccount(Long id); @Secured("IS_AUTHENTICATED_ANONYMOUSLY") public Account[] findAccounts(); @Secured("ROLE_TELLER") public Account post(Account account, double amount); }
The use of protect-pointcut
is particularly powerful, as it allows you to
apply security to many beans with only a simple declaration. Consider the following example:
<global-method-security> <protect-pointcut expression="execution(* com.mycompany.*Service.*(..))" access="ROLE_USER"/> </global-method-security>
This will protect all methods on beans declared in the application context whose classes
are in the com.mycompany
package and whose class names end in "Service".
Only users with the ROLE_USER
role will be able to invoke these methods.
As with URL matching, the most specific matches must come first in the list of pointcuts, as the
first matching expression will be used.
This alternative syntax allows you to specify security for a specific bean by adding this element within the bean itself.
<bean:bean id="target" class="com.mycompany.myapp.MyBean"> <intercept-methods> <protect method="set*" access="ROLE_ADMIN" /> <protect method="get*" access="ROLE_ADMIN,ROLE_USER" /> <protect method="doSomething" access="ROLE_USER" /> </intercept-methods> </bean:bean>
This allows you to configure security attributes for individual methods on the bean or simple wildcarded patterns.