Valid use case for @PostAuthorize And @PostFilter annotations
Asked Answered
R

2

24

We have just migrated to Spring Security 3.0.8 from 2.0.8 (Can' upgrade to the latestversion which is 3.2.X as our core spring libraries are still on 3.0.X, which we plan to upgrade later when business permits).

I understand that we now have annotations for securing methods like @PreAuthorize, @PostAuthorize, @Secured, @PreFilter and @PostFilter.

I understand the use of @PreAuthorize, which really makes sense. But can't think of any valid use cases where you would ever use @PostAuthorize or @PostFilter annotation?

Can somebody who used it please explain to me a reasonable use-case for using them?

Thanks in advance!

Roa answered 28/2, 2014 at 10:50 Comment(0)
C
25

Both the @PostAuthorize and @PostFilter are used, mostly, in combination with ACL. Where the @PostAuthorize will generate an exception if something is returned which one hasn't access to, the @PostFilter will remove the objects one doesn't have access to (in general useful when returning collections of elements).

Chrystal answered 28/2, 2014 at 12:51 Comment(1)
Brilliant! Thanks for that explanation. It would have been even better if there was an example, nevertheless I'll accept the answer!Roa
L
6

@PostFilter filters the returned collection or arrays after executing the method. Spring security provides a built-in object named as filterObject at which @PostFilter performs filtering task.

@PostFilter can be used on service layer with @PreAuthorize and @PostAuthorize.

Use interface to declare the filter operation.

public interface IBookService {

    @PreAuthorize ("hasRole('ROLE_READ')")
    @PostFilter ("filterObject.owner == authentication.name")
    public List<Book> getBooks();
    
    @PreAuthorize("filterObject.owner == authentication.name")
    public void addBook(List<Book> books);

}
Lysozyme answered 29/10, 2015 at 1:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.