在Spring @PreAuthorize中调用私有方法

M99*_*M99 11 spring spring-mvc spring-security

我正在使用Spring Security对方法进行权限检查.我想调用一个私有方法来收集一些数据发送给hasPermission()方法.以下是我想要执行的东西,我得到SpelEvaluationException,因为Spring正在寻找localPrivateMethodin MethodSecurityExpressionRoot.有没有办法实现这个目标?谢谢.

@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) {}
Run Code Online (Sandbox Code Playgroud)

dig*_*oel 25

您将无法调用私有方法,但您可以在另一个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
}
Run Code Online (Sandbox Code Playgroud)

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
    }
}
Run Code Online (Sandbox Code Playgroud)

和PermissionEvaluator是我自己的界面,没有什么特别的,只是我需要评估的任何方法.

  • PermissionEvaluator 是一个现有的 Spring Security 接口,至少在 spring security core 5.1.5 中是这样,所以这段代码将不起作用,因为您没有实现 PermissionEvaluator 中的方法。如果您不打算使用 PermissionEvaluator,我建议您重命名您的自定义界面。 (3认同)