Call a private method in Spring @PreAuthorize

前端 未结 2 1116
一个人的身影
一个人的身影 2021-02-04 04:30

I am using Spring Security for permission checking on methods. I would like to call a private method to collect some data to send to hasPermission() method. Followi

相关标签:
2条回答
  • 2021-02-04 05:13

    You will not be able to call a private method, but you will be able to call a method in another spring bean. In my app I have an @Component named permissionEvaluator. I then reference it in a @PreAuthorize like so:

    @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 with nothing special, just whatever methods I need to evaluate.

    0 讨论(0)
  • 2021-02-04 05:21

    Private methods cannot be called, but you can refer to "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 讨论(0)
提交回复
热议问题