I have been looking for a way to 开发者_StackOverflow中文版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:
- How is this best done with Spring Security?
- How is this done when /owners/{ownerId}/pets/new is accessed via async request?
- How would I access above-mentioned URI from a 3rd party app, e.g. iPhone app?
- Any sample/reference applications/articles?
Thanks Er
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.
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.
精彩评论