Call private method in Spring @PreAuthorize

I use Spring Security to check method permissions. I would like to call a private method to collect some data to send to the hasPermission () method. The following is what I am trying to execute, and I am getting a SpelEvaluationException because Spring is looking for the local PrivateMethod method in MethodSecurityExpressionRoot. Is there any way to achieve this? Thanks.

@PreAuthorize("hasPermission(new Object[]{#arg3, #localPrivateMethod(#arg1,#arg2)}, 'canDoThis')") public long publicMethod1(long arg1, long arg2, long arg3) { } private String localPrivateMethod(long a1, long a2) { } 
+6
source share
2 answers

You cannot call a private method, but you can call a method in another spring bean. In my application, I have @Component named permissionEvaluator. Then I refer to @PreAuthorize as follows:

 @PreAuthorize("@permissionEvaluator.canViewImageSet( #imageSet, principal )") @RequestMapping(value="/image", method=RequestMethod.GET ) public String getImage( @RequestParam(value="imageSet", required=false) ImageSet imageSet ) { // method body } 

PermissionEvaluatorImpl looks like this:

 @Component(value="permissionEvaluator") public class PermissionEvaluatorImpl implements PermissionEvaluator { public PermissionEvaluatorImpl() {} /** * Determine if a user can view a given image. */ public boolean canViewImageSet( ImageSet imageSet, UserDetailsAdapter user ) { // code to see if they should view this image } } 

and PermissionEvaluator is my own interface, which is nothing special, just whatever methods I have to evaluate.

+20
source

Private methods cannot be called, but you can access this component through this. :

 @PreAuthorize("hasPermission(new Object[]{#arg3, /* HERE: */ this.localPublicMethod(#arg1,#arg2)}, 'canDoThis')") public long publicMethod1(long arg1, long arg2, long arg3) { } public String localPublicMethod(long a1, long a2) { } 
0
source

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


All Articles