4. Code Example

Example 1. Excerpt from PersonDao

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 actual DAO interface, even if a non-admin user tries to execute the delete URL they will not be able to delete a record. Try to delete a user as a non-admin user to see the request being stopped by Spring Security (ex: http://www.springbyexample.org/simple-security/delete/person.html?id=1).

                
public interface PersonDao {

    /**
     * Find person by id.
     */
    public Person findPersonById(Integer id);

    /**
     * Find persons.
     */
    public Collection<Person> findPersons();

    /**
     * Find persons using a start index and max number of results.
     */
    public Collection<Person> findPersons(final int startIndex, final int maxResults);

    /**
     * Find persons by last name.
     */
    public Collection<Person> findPersonsByLastName(String lastName);

    /**
     * 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.