Comprehensive Guide to Casbin: Enhancing Access Control for Your Application
Casbin is a powerful and efficient open-source access control library that supports various access control models. It is widely used in applications to handle different levels of permissions and security. In this guide, we will introduce you to Casbin and explore dozens of its useful APIs with code snippets.
Getting Started with Casbin
package main
import (
"github.com/casbin/casbin/v2"
"github.com/casbin/casbin/v2/model"
)
func main() {
e, err := casbin.NewEnforcer("path/to/model.conf", "path/to/policy.csv")
if err != nil {
panic(err)
}
e.AddPolicy("alice", "data1", "read")
e.Enforce("alice", "data1", "read") // true
}
Understanding Casbin APIs
1. Adding Policies
e.AddPolicy("alice", "data1", "read")
e.AddPolicy("bob", "data2", "write")
2. Removing Policies
e.RemovePolicy("alice", "data1", "read")
3. Enforcing Policies
allowed, err := e.Enforce("alice", "data1", "read")
if err != nil {
panic(err)
}
if allowed {
// permit alice to read data1
} else {
// deny the request
}
4. Loading Policies from File
err := e.LoadPolicy()
5. Saving Policies to File
err := e.SavePolicy()
Example Application Using Casbin
Let’s build an example web application using Casbin for access control.
Setting Up Model and Policy
// model.conf
[request_definition]
r = sub, obj, act
[policy_definition]
p = sub, obj, act
[policy_effect]
e = some(where (p.eft == allow))
[matchers]
m = r.sub == p.sub && r.obj == p.obj && r.act == p.act
// policy.csv
p, alice, /data1, read
p, bob, /data2, write
Building the Application
package main
import (
"net/http"
"github.com/casbin/casbin/v2"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
e, _ := casbin.NewEnforcer("model.conf", "policy.csv")
r.GET("/data1", func(c *gin.Context) {
sub := c.Query("user")
obj := "data1"
act := "read"
if ok, _ := e.Enforce(sub, obj, act); ok {
c.JSON(http.StatusOK, gin.H{"data": "data1 content"})
} else {
c.JSON(http.StatusForbidden, gin.H{"error": "Access denied"})
}
})
r.GET("/data2", func(c *gin.Context) {
sub := c.Query("user")
obj := "data2"
act := "write"
if ok, _ := e.Enforce(sub, obj, act); ok {
c.JSON(http.StatusOK, gin.H{"data": "data2 content"})
} else {
c.JSON(http.StatusForbidden, gin.H{"error": "Access denied"})
}
})
r.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
}
With this application, you can enforce access control policies for different users trying to access different resources within your application. Casbin provides a flexible and powerful way to manage these permissions.
Hash: b14a6bb205e7b7ac7ea0b175cce38d60498112a51b4995046194dea144b8ab07