jcasbin-mongodb-adapter is the MongoDB adapter for jCasbin. With this library, jCasbin can load policy from a MongoDB database or save policy to it.
For Maven:
<dependency>
<groupId>org.casbin</groupId>
<artifactId>jcasbin-mongo-adapter</artifactId>
<version>LATEST</version>
</dependency>
optional: If your project already has a mongodb driver, please ignore it.
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-sync</artifactId>
<version>${mongodb.version}</version>
</dependency>
package org.casbin.adapter;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoDatabase;
import org.casbin.jcasbin.main.Enforcer;
import org.casbin.jcasbin.persist.Adapter;
import org.jim.jcasbin.MongoAdapter;
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
// Use MongoDB connection string and database name to initialize a MongoAdapter.
String connectionString = "mongodb://localhost:27017/";
MongoClient mongoClient = MongoClients.create(connectionString);
MongoDatabase database = mongoClient.getDatabase("casbin");
// Check and create a collection
if (!database.listCollectionNames().into(new ArrayList<>()).contains("casbin_rule")) {
database.createCollection("casbin_rule");
}
Adapter adapter = new MongoAdapter(mongoClient, "casbin");
Enforcer enforcer = new Enforcer("examples/rbac_model.conf", "examples/rbac_policy.csv");
// Check the permission.
enforcer.enforce("alice", "data1", "read");
// Modify the policy.
// enforcer.addPolicy(...);
// enforcer.removePolicy(...);
// Save the policy back to DB.
adapter.savePolicy(enforcer.getModel());
// Close the MongoDB client.
mongoClient.close();
}
}
This project is under Apache 2.0 License. See the LICENSE file for the full license text.