Spring Security - Ownership based access
For a simple get operation you can just return the post linked to your current logged in user
@GetMapping
public Post getPost(Authentication authentication) {
return service.getPostByUser(authentication.getName());
}
For updating an existing post, you can check within the PreAuthorize if the creator is the logged in user. authentication.getName() gives back an email in my example
@PutMapping
@PreAuthorize("#post.getCreator() == authentication.getName()")
public void update(@RequestBody Post post, Authentication authentication) {
service.updatePost(post);
}
Basic example of the @Component way
@Autowired
private CreatorCheck creatorCheck;
@PutMapping
@PreAuthorize("@creatorChecker.check(#post,authentication)")
public void update(@RequestBody Post post, Authentication authentication) {
service.updatePost(post);
}
And the component.. Can be extended to retrieve the original Post and check that creator..
@Component
public class CreatorCheck {
public boolean check(Post post, Authentication authentication) {
return post.getCreator().equals(authentication.getName());
}
}
For a more comprehensive tutorial check out this tutorial link found by 0x1C1B