id |
---|
casbin |
Casbin middleware for Fiber.
Note: Requires Go 1.18 and above
go get -u github.com/gofiber/fiber/v2
go get -u github.com/gofiber/contrib/casbin
choose an adapter from here
go get -u github.com/casbin/xorm-adapter
casbin.New(config ...casbin.Config) *casbin.Middleware
Property | Type | Description | Default |
---|---|---|---|
ModelFilePath | string |
Model file path | "./model.conf" |
PolicyAdapter | persist.Adapter |
Database adapter for policies | ./policy.csv |
Enforcer | *casbin.Enforcer |
Custom casbin enforcer | Middleware generated enforcer using ModelFilePath & PolicyAdapter |
Lookup | func(*fiber.Ctx) string |
Look up for current subject | "" |
Unauthorized | func(*fiber.Ctx) error |
Response body for unauthorized responses | Unauthorized |
Forbidden | func(*fiber.Ctx) error |
Response body for forbidden responses | Forbidden |
package main
import (
"github.com/gofiber/fiber/v2"
"github.com/gofiber/contrib/casbin"
_ "github.com/go-sql-driver/mysql"
"github.com/casbin/xorm-adapter/v2"
)
func main() {
app := fiber.New()
authz := casbin.New(casbin.Config{
ModelFilePath: "path/to/rbac_model.conf",
PolicyAdapter: xormadapter.NewAdapter("mysql", "root:@tcp(127.0.0.1:3306)/"),
Lookup: func(c *fiber.Ctx) string {
// fetch authenticated user subject
},
})
app.Post("/blog",
authz.RequiresPermissions([]string{"blog:create"}, casbin.WithValidationRule(casbin.MatchAllRule)),
func(c *fiber.Ctx) error {
// your handler
},
)
app.Delete("/blog/:id",
authz.RequiresPermissions([]string{"blog:create", "blog:delete"}, casbin.WithValidationRule(casbin.AtLeastOneRule)),
func(c *fiber.Ctx) error {
// your handler
},
)
app.Listen(":8080")
}
package main
import (
"github.com/gofiber/fiber/v2"
"github.com/gofiber/contrib/casbin"
_ "github.com/go-sql-driver/mysql"
"github.com/casbin/xorm-adapter/v2"
)
func main() {
app := fiber.New()
authz := casbin.New(casbin.Config{
ModelFilePath: "path/to/rbac_model.conf",
PolicyAdapter: xormadapter.NewAdapter("mysql", "root:@tcp(127.0.0.1:3306)/"),
Lookup: func(c *fiber.Ctx) string {
// fetch authenticated user subject
},
})
// check permission with Method and Path
app.Post("/blog",
authz.RoutePermission(),
func(c *fiber.Ctx) error {
// your handler
},
)
app.Listen(":8080")
}
package main
import (
"github.com/gofiber/fiber/v2"
"github.com/gofiber/contrib/casbin"
_ "github.com/go-sql-driver/mysql"
"github.com/casbin/xorm-adapter/v2"
)
func main() {
app := fiber.New()
authz := casbin.New(casbin.Config{
ModelFilePath: "path/to/rbac_model.conf",
PolicyAdapter: xormadapter.NewAdapter("mysql", "root:@tcp(127.0.0.1:3306)/"),
Lookup: func(c *fiber.Ctx) string {
// fetch authenticated user subject
},
})
app.Put("/blog/:id",
authz.RequiresRoles([]string{"admin"}),
func(c *fiber.Ctx) error {
// your handler
},
)
app.Listen(":8080")
}