跳转至主要内容

Policy Subset Loading

Some adapters support filtered policy loading. This capability loads only a subset of policies from storage based on specified criteria, enabling efficient enforcement in large multi-tenant environments where loading all policies would create a performance bottleneck.

To load filtered policies with a supported adapter, call LoadFilteredPolicy. The filter format depends on the adapter implementation. The SavePolicy method is disabled when operating with filtered policies to prevent accidental data loss.

Here's an example using the built-in filtered file adapter with an RBAC model that includes domains. This filter restricts loaded policies to a single domain, excluding all policies for other domains:

import (
"github.com/casbin/casbin/v3"
fileadapter "github.com/casbin/casbin/v3/persist/file-adapter"
)

enforcer, _ := casbin.NewEnforcer()

adapter := fileadapter.NewFilteredAdapter("examples/rbac_with_domains_policy.csv")
enforcer.InitWithAdapter("examples/rbac_with_domains_model.conf", adapter)

filter := &fileadapter.Filter{
P: []string{"", "domain1"},
G: []string{"", "", "domain1"},
}
enforcer.LoadFilteredPolicy(filter)

// The loaded policy now only contains the entries pertaining to "domain1".

The LoadIncrementalFilteredPolicy method provides similar functionality but appends filtered policies to existing policies rather than replacing them. This incremental approach lets you build up policies from multiple filtered loads.