Spring-Boot: Can not Create Custom Security Expression

Viewed 399

I am using Spring boot 2.4.1 and am following the instructions from link to create a Custom Security Expression. Unfortunately, I can't createSecurityExpressionRoot method and my annotation also doesn't work.

I get an error when calling into api

[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.IllegalArgumentException: Failed to evaluate expression 'hasAccessToCollection('Administrator')'] with root cause

org.springframework.expression.spel.SpelEvaluationException: EL1004E: Method call: Method hasAccessToCollection(java.lang.String) cannot be found on type org.springframework.security.access.expression.method.MethodSecurityExpressionRoot

My Service

@PreAuthorize("hasAccessToCollection('Administrator')")
    public Map getCustomPermission() {
        Map<String, String> response  = new HashMap<String, String>() {{
            put("message", "Successful");
        }};
        return response;
    }

My CustomMethodSecurityExpressionRoot

public class CustomMethodSecurityExpressionRoot 
        extends SecurityExpressionRoot implements MethodSecurityExpressionOperations {

    
    public IcodeMethodSecurityExpressionRoot(Authentication authentication) {
        super(authentication);
    }
    
    public boolean hasAccessToCollection(String permission) {
        return true;
    }
    
    public boolean hasAccessToCollection(String permission, String attribute) {
        return true;
    }
    ...
}

My CustomMethodSecurityExpressionHandler

public class CustomMethodSecurityExpressionHandler extends DefaultMethodSecurityExpressionHandler  {
    private AuthenticationTrustResolver trustResolver = 
      new AuthenticationTrustResolverImpl();

    protected MethodSecurityExpressionOperations createSecurityExpressionRoot(
      Authentication authentication, MethodInvocation invocation) {
        CustomMethodSecurityExpressionRoot root = 
          new CustomMethodSecurityExpressionRoot(authentication);
        root.setPermissionEvaluator(getPermissionEvaluator());
        root.setTrustResolver(this.trustResolver);
        root.setRoleHierarchy(getRoleHierarchy());
        return root;
    }
}
0 Answers
Related