【问题标题】:How to restrict resources to those owned by the current user如何将资源限制为当前用户拥有的资源
【发布时间】:2015-09-10 07:36:50
【问题描述】:

我有一个父对象,它属于一个用户(在弹簧安全意义上)。

我想使用 spring-data-rest 的所有优点,但不必重写大量、修改查询等以按当前用户过滤。

有没有简单的方法可以做到这一点?

总结一下,我想要这样的东西:

@PreAuthorize("hasRole('USER')")
@RepositoryRestResource(collectionResourceRel = "tasks", path="tasks")
public interface TaskRepository extends PagingAndSortingRepository<Task, Long> {}

...当我转到“/tasks”时,它只显示属于经过身份验证的用户的任务。如果我不需要,我不想使用像“/users/foo/tasks”这样的网址。

这可行吗?

【问题讨论】:

    标签: spring spring-data-rest


    【解决方案1】:

    我建议@Override 个别方法以保护实体。

    @PreAuthorize("hasRole('USER')")
    @RepositoryRestResource(collectionResourceRel = "tasks", path="tasks")
    public interface TaskRepository extends PagingAndSortingRepository<Task, Long> {
        @PostAuthorize("returnObject.owner.username == principal.username")
        Task findOne(Long id);
    }
    

    http://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#access-control-using-preauthorize-and-postauthorize

    【讨论】:

      【解决方案2】:

      你可以在控制器层做如果父对象封装了用户信息,在web服务方法上使用@PostAuthorize注解...希望对你有帮助

      @PostAuthorize("returnObject.body.username == principal.username")
      @RequestMapping(value = "/{id}", method = RequestMethod.GET)
      public ResponseEntity<ParentDTO> getParent(@PathVariable(value = "id") Integer id) {
         ...........
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-11
        • 1970-01-01
        相关资源
        最近更新 更多