首页 > 解决方案 > 用自定义注解继承@PreAuthorize注解,用于spring自定义方法安全表达式

问题描述

我已经在我的 Spring Boot 项目中成功实现了自定义方法安全表达式。

这是我的表达式根:

public class CustomMethodSecurityExpressionRoot extends SecurityExpressionRoot implements MethodSecurityExpressionOperations {

    public boolean checkTwoParamsAreEqual(Long param1, Long param2){
        return param1.equals(param2);
    }

    //constructor and overridden methods ignored for brevity

}

方法安全表达式的所有其他必需配置和处理程序均已正确实现。

在我的控制器类中,我做了:

@GetMapping("/test")
@PreAuthorize("checkTwoParamsAreEqual(#id1, #id2)")
public String tst( @RequestParam("id1") Long id1, @RequestParam("id2") Long id2){
   return "Voila!!!";
}

有了这个,当我用相同的值id1id2请求参数发出获取请求时,它会返回Voila!!!,对于不同的请求参数值,它会抛出 403 异常。这正是我想要的。


现在,我想通过为@PreAuthorize.

我的自定义注释定义为:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Inherited
@PreAuthorize("checkTwoParamsAreEqual(#id1, #id2)")
public @interface PreCheckParamsAreEqual {
}

而且,我通过以下方式更新了我的控制器:

@GetMapping("/test")
@PreCheckParamsAreEqual
public String tst( @RequestParam("id1") Long id1, @RequestParam("id2") Long id2){
   return "Voila!!!";
}

通过此更改,无论我为请求参数传递什么值id1id2它们总是返回“瞧!!!”。我想不出如何使用参数创建自定义注释的方法。

标签: javaspringspring-bootspring-securityannotations

解决方案


推荐阅读