title: Securing a Spring Data RepositoryRestResource (CrudRepository) over HTTP, but not internally
body: <p>I have a Spring Data project that uses RepositoryRestResource and CrudRepository's to expose entities over REST. I need to be able to secure the repository when it is accessed over HTTP, but not have it secured when used internally (in service layers, for example).</p>
  
  <p>I have spring security up and running, but adding annotations like PreAuthorize on the CrudRepository methods, also causes the security expressions to be executed when I'm calling those methods from within my service layer.</p>
  
  <p>I'd be glad if someone could point me in the right direction with this.</p>
  
  <p><strong>EDIT 1</strong></p>
  
  <p>I've tried removing the Rest Export and security annotations from the UserRepository for use internally, then subclassing UserRepository as UserRepositoryRestExported, exporting and securing that one. However I'm seeing some inconsistent implementation of the security annotations between runs, which makes me wonder if Spring is exporting UserRepositoryRestExported sometimes, and UserRepository other times...?</p>
  
  <p><strong>EDIT 2</strong></p>
  
  <p>Here's the code described in edit 1</p>
  
  <p>UserRepository.java</p>
  
  <pre><code>@Component("UserRepository")
  public interface UserRepository extends CrudRepository&lt;User, Long&gt; {
  
      // .. some extra methods
  
  }
  </code></pre>
  
  <p>UserRepositoryRest.java</p>
  
  <pre><code>@Component("UserRepositoryRest")
  @RepositoryRestResource(collectionResourceRel = "users", path = "users")
  public interface UserRepositoryRest extends UserRepository {
  
      @PostAuthorize("authentication.name == returnObject.getName() || hasRole('ROLE_ADMIN')")
      @Override
      User findOne(Long id);
  
      @PostFilter("authentication.name == filterObject.getName() || hasRole('ROLE_ADMIN')")
      @Override
      Iterable&lt;User&gt; findAll();
  
      @PreAuthorize("principal.getCell() == #user.getName() || hasRole('ROLE_ADMIN')")
      @Override
      void delete(@P("user") User user);
  
      User save(User entity);
  
      long count();
  
      boolean exists(Long primaryKey);
  
  }
  </code></pre>