Securing exclusively the REST access to a Spring Data Rest Repository

One solution would be to remove the @PreAuthorize annotation from your repository interface, and in a configuration class, extend WebSecurityConfigAdaptor and override the configure(HttpSecurity security) method. From here you can use AntMatchers to impose access restrictions to the REST endpoints as required. For example:

protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests().antMatchers("/someEntities/**").hasRole('ADMIN')
    .anyRequest().permitAll();   
}

See http://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#jc-httpsecurity for more details.


Please evaluate these possibilities:

  • Security checks in REST event handlers
  • Adding custom repository methods for internal use
  • Using RunAsManager (or temporarily switching SecurityContext to perform a privileged operation)

Securing modifying requests using REST event handlers:

@Service
@RepositoryEventHandler
public class FooService {

  /**
   * Handles before-* events.
   */
  @HandleBeforeCreate
  @HandleBeforeSave
  @HandleBeforeDelete
  @PreAuthorize("hasRole('ADMIN')")
  public void onBeforeModify(final Foo entity){
    // noop
  }

  /**
   * Handles before-* events.
   */
  @HandleBeforeLinkSave
  @HandleBeforeLinkDelete
  @PreAuthorize("hasRole('ADMIN')")
  public void onBeforeModifyLink(final Foo entity, final Object linked){
    // noop
  }
}

Securing standard CRUD methods while adding non-secure custom methods on repository for internal use:

public interface FooDao extends CrudRepository<Foo, Long> {

 @Override
 @PreAuthorize("hasRole('ADMIN')")
 <S extends Foo> S save(final S entity);

  /**
   * Saves entity without security checks.
   */
  @Transactional
  @Modifying
  default <S extends Foo> S saveInternal(final S entity) {
    return save(entity);
  }
}