qnhant5010
qnhant5010

Reputation: 305

Secure method of spring data rest repository

I am currently developping a REST API server based on Spring Boot. Thanks to Spring Data Rest, the 10-ish entities can easily have their own controller via a simple repository (@RepositoryRestResource plus JpaRepository and JpaSpecificationExecutor). Now i need to integrate the security control with @PreAuthorize.

The question here is which method should I put the annotation on to restrain GET / POST / etc. ?

For example, if I limit the permission of delete, does it affect similarly on deleteById, deleteInBatch, deleteAll? I see in the documentation the annotation of exported is put on deleteById and delete without any further explanation, which confuses me.

Upvotes: 0

Views: 1643

Answers (1)

Marc Tarin
Marc Tarin

Reputation: 3169

For example, if I limit the permission of delete, does it affect similarly on deleteById, deleteInBatch, deleteAll?

To the best of my knowledge: no. Check this sample code where searches are authorized, but deletion is strictly limited to admins only:

public interface RecordRepository<T extends Record> extends MongoRepository<T, String> {

    // paginated queries
    @RestResource(path = "names", rel = "name")
    public Page<T> findByName(@Param("name") String name, Pageable pageable);
    @RestResource(path = "types", rel = "types")
    public Page<T> findByTypeIn(@Param("type") List<String> types, Pageable pageable);

    // restrict delete operations to administrators only

    @PreAuthorize("hasRole('ADMIN')")
    @Override
    void deleteById(String id);

    @PreAuthorize("hasRole('ADMIN')")
    @Override
    void delete(T entity);

    @PreAuthorize("hasRole('ADMIN')")
    @Override
    void deleteAll(Iterable<? extends T> records);

    @PreAuthorize("hasRole('ADMIN')")
    @Override
    void deleteAll();
}

That being said, if your purpose is to restrict deletion to admins only, you can extend WebSecurityConfigurerAdapter and configure it to block all http DELETE requests:

public class WebSecurityBaseConfiguration extends WebSecurityConfigurerAdapter {
    ...

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
          .antMatchers(HttpMethod.DELETE).hasRole("ADMIN");
    }

}

Note that this is a quick and dirty copy paste that may not work out of the box (you will probably need to configure a role hierarchy).

Upvotes: 1

Related Questions