Spring Saving Data: Returning User Resource

I am creating a simple CRUD application (shopping list) with Spring Boot and Spring Data Rest. I have a resource: ShoppingItem . Is there an easy way to just return resources belonging to the user who sends the request? (Support for multiple users). Thus, the user gets their own ShoppingItems, and not every ShoppingItem. Or do I need to implement the controller myself, where do I do it?

I found Spring user-based REST data filtering data for this approach for user-based resource filtering, but that will not help me in the endpoint repository.

Thanks in advance

+1
java spring spring-data-rest spring-security
source share
3 answers

If you use Spring Security Integration, you can use an ACL (possibly heavy) or a simple postFilter , as shown below:

 public interface ShoppingItemRepository extends CrudRepository<ShoppingItem, Long> { @PostFilter("filterObject.user.getId() == principal.id") @Override Iterable<ShoppingItem> findAll(); } 
+2
source share

I recently resolved this issue, see Spring Data Override Repositories (Controllers and AOP)

The most elegant solution I have found is using AOP, this sample with QueryDSL and Spring Data REST Repositories:

 @Aspect @Transactional @Component public class FilterProjectsAspect { @Pointcut("execution(* com.xxx.ProjectRepository.findAll(..))") public void projectFindAll() { } @Around("projectFindAll()") public Object filterProjectsByUser(final ProceedingJoinPoint pjp) throws Throwable { Object[] args = pjp.getArgs(); for (int i = 0; i < args.length; i++) { if (args[i] instanceof Predicate) { Predicate predicate=(Predicate) args[i]; BooleanExpression isProjectOwner =buildExpressionForUser() predicate = ExpressionUtils.allOf(isProjectOwner, predicate); args[i]=predicate; //Update args } return pjp.proceed(args); } } 
+1
source share

It is better to implement a controller for several reasons:

  • Imagine that your application has some kind of management interface for viewing all shopping lists (see as an administrator account).

  • Or do you need to manipulate the shopping list in some cron based job (where usage is absent)

0
source share

All Articles