Introduction to Casbin
Casbin is a powerful and efficient open-source access control library that supports multiple access control models. It is fast and flexible, making it an ideal choice for controlling access permissions in various applications. This guide covers the basics of Casbin and provides several useful API examples to help you get started.
Getting Started with Casbin
To begin using Casbin, you need to install it first. For Go, you can use:
go get github.com/casbin/casbin/v2
Basic API Usage
Here are some essential Casbin APIs for managing access control:
Create an Enforcer
e, _ := casbin.NewEnforcer("path/to/model.conf", "path/to/policy.csv")
Load Policies
e.LoadPolicy()
Enforce Permissions
ok, _ := e.Enforce("alice", "data1", "read") if ok {
// permit alice to read data1
} else {
// deny the request
}
Add a Policy
e.AddPolicy("bob", "data2", "write")
Remove a Policy
e.RemovePolicy("bob", "data2", "write")
Get All Roles
roles := e.GetAllRoles()
Add a Role for a User
e.AddRoleForUser("alice", "admin")
Remove a Role from a User
e.DeleteRoleForUser("alice", "admin")
Application Example
Here is an application example that demonstrates how to use the Casbin APIs introduced above:
package main
import (
"github.com/casbin/casbin/v2"
"log"
)
func main() {
e, err := casbin.NewEnforcer("path/to/model.conf", "path/to/policy.csv")
if err != nil {
log.Fatalf("Failed to create enforcer: %v", err)
}
// Load policies from the policy file
err = e.LoadPolicy()
if err != nil {
log.Fatalf("Failed to load policy: %v", err)
}
// Add a policy rule
e.AddPolicy("alice", "data1", "read")
// Add a role for a user
e.AddRoleForUser("bob", "admin")
// Save the policy back to the policy file
err = e.SavePolicy()
if err != nil {
log.Fatalf("Failed to save policy: %v", err)
}
// Enforce the policies
ok, err := e.Enforce("alice", "data1", "read")
if err != nil {
log.Fatalf("Failed to enforce policy: %v", err)
}
if ok {
log.Println("Access granted")
} else {
log.Println("Access denied")
}
}
Conclusion
Casbin offers a highly flexible and efficient way to manage access control in your applications. Its wide range of APIs, as demonstrated above, gives you granular control over permissions and roles in a variety of use cases. Start leveraging the power of Casbin today to ensure robust access management in your systems.
Hash: b14a6bb205e7b7ac7ea0b175cce38d60498112a51b4995046194dea144b8ab07