javaspringspring-bootspring-securityspring-el

Using SpEL to pass parameters in Spring/Spring security method


Dear Spring/Spring Security developers:

For this controller method in Spring Boot, I use PreAuthorize annotation in combination with hasPermission Method. My problem is how to pass the Enum value currectly to the hasPermission method using SpEL.

I get the this error: Unsatisfied dependency expressed through constructor parameter 0: No qualifying bean of type 'java.lang.String' available

@Component("Scope")
public enum ScopeEnum{

    UPDATE("update"), DELETE("delete");

    public final String name;

    ResourceScope(String name) {
        this.name= name;
    }
}

@PreAuthorize("hasPermission(#authentication, @Scope.UPDATE")
public ResponseEntity doUpdateOrDelete(Authorization authorization, ...) {
  // Code....

}

Solution

  • First, an enum class cannot be instantiated externally, so do not attempt to register an enum as a Spring bean. Moreover, Spring is unable to assist you in finding a constructor parameter of type String. Second, there is an error in your EL expression. Therefore, the final solution is to remove @Component and change the EL expression to @PreAuthorize("hasPermission(#authentication, T(yourEnumPackageName.ScopeEnum).UPDATE.name)").