首页 > 解决方案 > 如果 SpEL 执行失败,如何在 Java 中跳过 PreAuthorize?

问题描述

我已经使用一些自定义 SpEL 函数保护了我的 API 端点。但是,由于@PreAuthorize在构造 SpEL 表达式时出现异常,使用 SpEL 会导致运行时错误。我想在发生时@PreAuthorize返回 true SPELExecutionException

标签: javaspring-bootspring-securityspring-el

解决方案


由于@PreAuthorize 用于验证请求者是否具有所需的授权,因此如果出现系统错误,用户绕过此安全机制没有任何意义。

你仍然可以绕过这个。看看下面的片段:只是一个更正它是 SpEL

@PostMapping()
@PreAuthorize("#{@someBean.validateAccess('HAS_ACCESS_TO_MY_METHOD')}")
public ResponseEntity<?> myMethod(@RequestBody final MyRequestBody requestBody) {       
    //some logic
}

@Service
public class SomeBean {

    public boolean validateAccess(String permission){
        boolean isAuthorized = false;
        try{
             //some logic to authorize
             // set the hasAccess variable to true or false based on your logic
             isAuthorized = true;
        } catch (Exception e) {
             // if some exception occurs set it to true
            isAuthorized = true;
        }
        return isAuthorized;
    }
}

推荐阅读