This is an alternative to securing URL access in the web layer. Sometimes, it is also required to secure method invocation in the service layer by enforcing fine-grained security control on methods. This is because, sometimes, it's easier to control it on particular methods than filtering by address, which can be called by typing. We can secure method invocation using Spring Security in a declarative way. We can annotate methods declaration in a bean interface or its implementation class with @Secured
annotation and specify the access attributes as its value whose type is String[]
, and enable security for these annotated methods by adding <global-method-security>
in Spring-Security.xml
file. This can be done as follows:
<beans:beans xmlns="http://www.springframework.org/schema/security" xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd"> <!-- To allow standards-based @Secured annotation, enable secured-annotations --> <global-method-security secured-annotations="enabled" /> <http . . . . . . </beans>
The global-method-security
namespace is configured along with its secured-annotations="enabled"
attribute to enable annotation-based security. And annotate methods with @Secured
annotation to allow method access for one or more than one role:
public interface EmployeeService { @Secured("ROLE_USER", "ROLE_GUEST") public List<employee> employeeList(); @Secured("ROLE_USER", "ROLE_ADMIN") public Person employeeAdd(Employee employee); @Secured("ROLE_ADMIN") public Person employeeDelete(int employeeId); }