在Spring @PreAuthorize中调用私有方法


问题内容

我正在使用Spring
Security进行方法的权限检查。我想调用一个私有方法来收集一些要发送给hasPermission()方法的数据。以下是什么我尝试执行,我得到SpelEvaluationException因为春天正在寻找localPrivateMethodMethodSecurityExpressionRoot。有没有办法做到这一点?谢谢。

@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) {}

问题答案:

您将无法调用私有方法,但可以在另一个spring
bean中调用方法。在我的应用程序中,我有一个名为PermissionEvaluator的@Component。然后,我在@PreAuthorize中引用它,如下所示:

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

PermissionEvaluatorImpl看起来像这样:

@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
    }
}

和PermissionEvaluator是我自己的界面,没有什么特别的,不管我需要评估什么方法。