Reputation: 9813
I have been looking for a way to secure URLs like
@RequestMapping("/owners/{ownerId}/pets/new")
on user (not role) level, i.e. only owner with ID {ownerId} has access. Moreover, I want to secure RESTful design incl. async access to JSON services on owner level dynamically.
My questions:
Thanks Er
Upvotes: 1
Views: 1578
Reputation: 709
Use @PreAuthorize. You can use a Spring-EL expression like
@RequestMapping("/owners/{ownerId}/pets/new")
@PreAuthorize("#ownerId == principal.id)")
public void doSomething(@RequestParam Number ownerId);
The above code is only representative. Some details depend on your implementation.
Read more here.
Upvotes: 2
Reputation: 10293
Regarding your question 1, the simplest approach I can think of is - within your controller method you can first check for the user authorization based on the ID. The UserDetails is accessible from the SpringSecurityContext and you can retrieve ID of currently logged in user from it. The ID obtained from request URL is also accessible as path variable. If these two dont match you can simply throw an exception like AccessDeniedException. You may move this logic to a method in a BaseController which will act as superclass for all your Controllers and same method can be used by all controller methods for a similar check.
Upvotes: 1