Customizing user roles based on a kind of property in Spring Security

In my Spring application, I have major roles like ADMIN and USER.

Is it possible to define a user role, such as PHOTO_UPLOADER, which inherits from USER, but also adds a check whether the user making the call is the owner of the photo?

I am tired of repeating the same if (currentUser.id == photo.uploader.id) in my controller actions. This applies to other objects.

+6
source share
3 answers

You can handle this with the ACL, as suggested by Tomas Nurkevich. But Spring Securitz ACLs are complex and poorly documented. (The best resource I know for him is a book: Spring Security 3 - sponsored by Spring Security)

But if you really only need this simple if (currentUser.id == photo.uploader.id) test if (currentUser.id == photo.uploader.id) , I would recommend a different technique.

You can improve method safety expressions that you can use in @PreAuthorize annotations. How:

 @PreAuthorize("isPhotoOwner(#photo)") public void doSomething(final Photo photo) { 

To implement this expression isPhotoOwner , the kernel is really simple:

 public class ExtendedMethodSecurityExpressionRoot extends MethodSecurityExpressionRoot { public ExtendedMethodSecurityExpressionRoot(final Authentication a) { super(a); } /** * */ public boolean isPhotoOwner(final Photo photoObject) { if (photoObject == null) { return false; } Photo photo = (photo) photoObject; return photo.getCreator().getLogin().equals(authentication.getName()); } } 

Unfortunately, there is some extra work to register with ExtendedMethodSecurityExpressionRoot. --- I do not have time at the moment, if you are ready to try this approach, then leave a commit and I will tell the rest

+9
source

I do not know what types of data access you are using. I know that you can write an interceptor or event listener to check the security for sleep mode. I think the ibatis is also the same. in my project, I wrote CRUD resolution interface methods in the parent class of the model / entity and performed a security check on some events, for example, before loading an object. spring acl security is a bit complicated. implementing your security solution is better.

+1
source

Welcome to the world of ACLs - access control list. This tutorial is pretty old, but pretty comprehensive.

0
source

Source: https://habr.com/ru/post/909612/


All Articles