https://github.com/prongbang/fiber-casbinrest
Casbin RESTful Adapter on Fiber Web Framework
https://github.com/prongbang/fiber-casbinrest
adapter casbin-adapter fiber fiber-framework go golang role-api
Last synced: about 1 year ago
JSON representation
Casbin RESTful Adapter on Fiber Web Framework
- Host: GitHub
- URL: https://github.com/prongbang/fiber-casbinrest
- Owner: prongbang
- License: mit
- Created: 2020-10-11T08:26:28.000Z (over 5 years ago)
- Default Branch: master
- Last Pushed: 2025-04-27T04:15:29.000Z (about 1 year ago)
- Last Synced: 2025-05-01T21:36:21.064Z (about 1 year ago)
- Topics: adapter, casbin-adapter, fiber, fiber-framework, go, golang, role-api
- Language: Go
- Homepage:
- Size: 42 KB
- Stars: 10
- Watchers: 2
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# Fiber Casbin REST ๐ก๏ธ
[](https://codecov.io/gh/prongbang/fiber-casbinrest)
[](https://goreportcard.com/report/github.com/prongbang/fiber-casbinrest)
[](https://pkg.go.dev/github.com/prongbang/fiber-casbinrest)
[](https://opensource.org/licenses/MIT)
> RESTful adapter for [Casbin](https://github.com/casbin/casbin) on [Fiber](https://github.com/gofiber/fiber) web framework. Simplify your authorization with powerful and flexible access control.
## โจ Features
- ๐ **Simple Integration** - Easy to integrate with Fiber applications
- ๐ **JWT Support** - Built-in JWT token authentication
- ๐ฏ **Role-Based Access Control** - Fine-grained RBAC support
- ๐ **Custom Adapter** - Flexible adapter system for various storage backends
- ๐ฆ **MongoDB Support** - Ready-to-use MongoDB adapter
- โก **High Performance** - Optimized for speed and efficiency
## ๐ฆ Installation
```shell
go get github.com/prongbang/fiber-casbinrest
```
## ๐ Quick Start
### 1. Configure Casbin Model
Create `model.conf`:
```ini
[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 && (keyMatch(r.obj, p.obj) || keyMatch2(r.obj, p.obj)) && (r.act == p.act || regexMatch(r.act, p.act))
```
### 2. Define Policies
Example policies:
```
p, admin, /user/*, (GET)|(POST)
p, anonymous, /login, (GET)
p, admin, /admin/user/:id, (GET)|(POST)
```
### 3. Implement in Your Application
```go
import (
"github.com/casbin/casbin/v2"
"github.com/gofiber/fiber/v2"
fibercasbinrest "github.com/prongbang/fiber-casbinrest"
"log"
)
func main() {
e, _ := casbin.NewEnforcer("auth_model.conf", "policy.csv")
app := fiber.New()
app.Use(fibercasbinrest.NewDefault(e, "secret"))
app.Get("/admin/user/:id", func(c *fiber.Ctx) error {
return c.SendString("Hello, Admin! ๐")
})
log.Fatal(app.Listen(":3000"))
}
```
## ๐ JWT Authentication
The middleware supports JWT tokens with role claims:
```json
{
"sub": "1234567890",
"name": "John Doe",
"iat": 1516239022,
"roles": ["ADMIN"]
}
```
Example JWT token:
```
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJyb2xlcyI6WyJBRE1JTiJdfQ.oW8uC8uyL4nZSjcDGRkW3ZHoEoHShPD7ft0cppgvQe4
```
## ๐ ๏ธ Advanced Usage
### Custom Adapter
Create your own adapter for different storage backends:
```go
type redisAdapter struct {}
func NewRedisAdapter() fibercasbinrest.Adapter {
return &redisAdapter{}
}
func (r *redisAdapter) GetRoleByToken(reqToken string) ([]string, error) {
// Implement your token validation and role retrieval logic
if reqToken == "ADMIN_TOKEN" {
return []string{"admin"}, nil
}
return []string{"anonymous"}, nil
}
func main() {
adapter := NewRedisAdapter()
e, _ := casbin.NewEnforcer("auth_model.conf", "policy.csv")
app := fiber.New()
app.Use(fibercasbinrest.New(e, adapter))
app.Get("/admin/user/:id", func(c *fiber.Ctx) error {
return c.SendString("Hello, Admin! ๐")
})
log.Fatal(app.Listen(":3000"))
}
```
### MongoDB Integration
Use MongoDB as your policy storage:
```go
import (
mongodbadapter "github.com/casbin/mongodb-adapter/v3"
)
func main() {
a, _ := mongodbadapter.NewAdapter("127.0.0.1:27017")
e, _ := casbin.NewEnforcer("model.conf", a)
// Add policies
_, _ = e.AddPolicy("anonymous", "/login", "GET")
_, _ = e.AddPolicy("admin", "/admin", "(GET)|(POST)")
_, _ = e.AddPolicy("admin", "/admin/user/:id", "GET")
// Save and load policies
_ = e.SavePolicy()
_ = e.LoadPolicy()
app := fiber.New()
app.Use(fibercasbinrest.NewDefault(e, "secret"))
app.Get("/admin/user/:id", func(c *fiber.Ctx) error {
return c.SendString("Hello, Admin! ๐")
})
log.Fatal(app.Listen(":3000"))
}
```
## ๐ API Reference
### Middleware Functions
| Function | Description |
|----------|-------------|
| `NewDefault(e *casbin.Enforcer, secret string)` | Creates middleware with default JWT configuration |
| `New(e *casbin.Enforcer, adapter Adapter)` | Creates middleware with custom adapter |
### Adapter Interface
```go
type Adapter interface {
GetRoleByToken(reqToken string) ([]string, error)
}
```
## ๐ง Configuration Options
### Supported Matcher Functions
- `keyMatch`: URL path matching
- `keyMatch2`: URL path matching with wildcard support
- `regexMatch`: Regular expression matching
For more matcher functions, visit: [Casbin Functions](https://casbin.org/docs/en/function)
## ๐งช Testing Your Policies
Use the [Casbin Editor](https://casbin.org/editor/) to test and validate your policies online.
## ๐ค Contributing
Contributions are welcome! Please feel free to submit issues and pull requests.
## ๐ License
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
## ๐ Support
If you find this library helpful, please consider buying me a coffee:
[](https://www.buymeacoffee.com/prongbang)
## ๐ Related Projects
- [Casbin](https://github.com/casbin/casbin) - Authorization library
- [Fiber](https://github.com/gofiber/fiber) - Express-inspired web framework
- [MongoDB Adapter](https://github.com/casbin/mongodb-adapter) - MongoDB storage adapter for Casbin
---