同一个应用程序中有多个 PermissionEvaluator

Vik*_*ava 1 spring spring-security

我有一个基于我们自己的 acl 系统的自定义 PermissionEvaluator。我想添加另一个 PermissionEvaluator 实现。这可能与现有的 PermissionEvaluator 冲突。我怎样才能避免这种情况?为两个 PermissionEvaluators 引入某种聚合机制?提前致谢。

Vik*_*ava 8

所以我找到了解决这个问题的方法。我创建

public class EvaluatorsAggregator
    implements PermissionEvaluator
{

  private List<PermissionEvaluator> evaluators;

  public EvaluatorsAggregator(List<PermissionEvaluator> evaluators)
  {
    super();
    this.evaluators = evaluators;
  }

  @Override
  public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission)
  {
    return evaluators.stream()
        .map(ev -> ev.hasPermission(authentication, targetDomainObject, permission))
        .reduce(Boolean::logicalOr)
        .orElse(false);
  }

  @Override
  public boolean hasPermission(
      Authentication authentication,
      Serializable targetId,
      String targetType,
      Object permission)
  {
    return false;
  }
}
Run Code Online (Sandbox Code Playgroud)

然后在配置文件中我添加了所有需要的评估器:

@Configuration
@Lazy(true)
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class Config
{

  @Autowired
  Repository repository1;

  @Autowired
  Repository repository2;

  @Bean
  public PermissionEvaluator permissionEvaluator()
  {
    List<PermissionEvaluator> evaluators = new ArrayList<>();
    evaluators.add(new PermissionEvaluator1(repository1));
    evaluators.add(new PermissionEvaluator2(repository2));
    return new EvaluatorsAggregator(evaluators);
  }
}
Run Code Online (Sandbox Code Playgroud)

也许这可以帮助某人。