Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to restrict resources to those owned by the current user

I have a parent object, which belongs to a user (in the spring-security sense).

I want to use all of the niceties of spring-data-rest, but without having to override a ton, modify queries etc. in order to filter by the current user.

Is there an easy way to do this?

Just to summarize, I want something like this:

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

... where when I go to "/tasks" it shows me only the tasks that belong to the authenticated user. I do not want to have to use urls like "/users/foo/tasks" if I don't have to.

Is this doable?

like image 205
Laran Evans Avatar asked Oct 31 '22 19:10

Laran Evans


2 Answers

I suggest @Override the individual methods in order to secure the entity.

@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

like image 187
John Giotta Avatar answered Dec 07 '22 07:12

John Giotta


You can do it in controller layer If the parent object encapsulate user information, use @PostAuthorize annotation on web services methods ... hope it will help you

@PostAuthorize("returnObject.body.username == principal.username")
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public ResponseEntity<ParentDTO> getParent(@PathVariable(value = "id") Integer id) {
   ...........
}
like image 33
MK-rou Avatar answered Dec 07 '22 08:12

MK-rou