首页 > 解决方案 > Spring-Boot:无法创建自定义安全表达式

问题描述

我正在使用 Spring boot 2.4.1 并按照链接中的说明创建自定义安全表达式。不幸的是,我无法创建SecurityExpressionRoot 方法,并且我的注释也不起作用。

调用 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

我的服务

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

我的 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;
    }
    ...
}

我的 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;
    }
}

标签: spring-bootspring-security

解决方案


推荐阅读