-1

I have protected my API endpoints using some custom SpEL functions. However, since using SpEL in @PreAuthorize can lead to run time errors due to exceptions in constructing the SpEL expression. I would like to make @PreAuthorize return true when an SPELExecutionException occurs.

Nikolai Shevchenko
  • 7,083
  • 8
  • 33
  • 42

1 Answers1

0

Since @PreAuthorize is used to validate if the requestor has the required authorization, It doesn't make any sense for the user to by-pass this security mechanism in case of system errors.

You can still by-pass this. Have a look at the snippet below: Just a correction it is 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;
    }
}
Sagar Ahuja
  • 637
  • 10
  • 10
  • Hi @Sagar, This is not what I am looking for. What I am talking about is reducing Run Time errors that render the API endpoint unusable because of a code error. As an example: consider a developer writing the function as: `@PreAuthorize("hasPermisson('#id','id')")` --- this is a simple typo which will result in a SpEL excecution error and render the API endpoint unusable and I would like to either catch *this error at compile time* or *bypass such execution errors and return true*. The try/catch block you have shown will only work if a method is called. – Sajjan Kumar Jain Dec 09 '19 at 04:12
  • As of now, I don't think it is supported But you can still look at the docs (https://docs.spring.io/spring/docs/4.1.x/spring-framework-reference/html/expressions.html#expressions-compiler-configuration) – Sagar Ahuja Dec 09 '19 at 09:16