Example 1. PersonService
The delete method has access restricted to users in the admin role by putting the @Secured
annotation above it and setting
the allowed roles. Which in this case is only the 'ROLE_ADMIN' role. By securing the service interface, even if a non-admin user tries
to execute the delete URL they will not be able to delete a record.
public interface PersonService { /** * Find person by id. */ public Person findById(Integer id); /** * Find persons. */ public Collection<Person> find(); /** * Saves person. */ public Person save(Person person); /** * Deletes person. */ @Secured ({"ROLE_ADMIN"}) public void delete(Person person); }
You may wonder why the '/delete/person*' URL wasn't restricted. For the current application, this would have been sufficient. But we don't really want to restrict the URL, we want to restrict the actual delete action. Spring Security makes it very easy to restrict access to actual methods. If at some point in the future the another URL is made to also delete a record, our rule will still be enforced. Also, if at some point someone creates a method that calls delete that is accessed by a completely different URL, only admins will be able to execute this new part of the application successfully. A new implementation of the interface will also have the same rule applied to since the security annotation was placed on the interface and not the implementation itself.