{"id":15695765,"url":"https://github.com/prongbang/casbinrest","last_synced_at":"2025-05-08T21:28:18.069Z","repository":{"id":87919544,"uuid":"193308621","full_name":"prongbang/casbinrest","owner":"prongbang","description":"Casbin RESTful adapter for Casbin https://github.com/casbin/casbin","archived":false,"fork":false,"pushed_at":"2022-01-12T10:21:48.000Z","size":16,"stargazers_count":6,"open_issues_count":1,"forks_count":1,"subscribers_count":2,"default_branch":"master","last_synced_at":"2024-10-10T19:11:09.198Z","etag":null,"topics":["adapter","casbin","echo-casbin","golang","role-api","roles"],"latest_commit_sha":null,"homepage":"","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/prongbang.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2019-06-23T05:06:43.000Z","updated_at":"2024-09-22T03:30:00.000Z","dependencies_parsed_at":null,"dependency_job_id":"e69db94c-3448-402a-be72-87469a9b693d","html_url":"https://github.com/prongbang/casbinrest","commit_stats":null,"previous_names":[],"tags_count":8,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/prongbang%2Fcasbinrest","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/prongbang%2Fcasbinrest/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/prongbang%2Fcasbinrest/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/prongbang%2Fcasbinrest/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/prongbang","download_url":"https://codeload.github.com/prongbang/casbinrest/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":221248607,"owners_count":16784765,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["adapter","casbin","echo-casbin","golang","role-api","roles"],"created_at":"2024-10-03T19:04:39.598Z","updated_at":"2025-05-08T21:28:18.063Z","avatar_url":"https://github.com/prongbang.png","language":"Go","funding_links":["https://www.buymeacoffee.com/prongbang"],"categories":[],"sub_categories":[],"readme":"# casbinrest 🔐\n\n[![Codecov](https://img.shields.io/codecov/c/github/prongbang/casbinrest.svg)](https://codecov.io/gh/prongbang/casbinrest)\n[![Go Report Card](https://goreportcard.com/badge/github.com/prongbang/casbinrest)](https://goreportcard.com/report/github.com/prongbang/casbinrest)\n[![Go Reference](https://pkg.go.dev/badge/github.com/prongbang/casbinrest.svg)](https://pkg.go.dev/github.com/prongbang/casbinrest)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\n\n\u003e RESTful adapter for [Casbin](https://github.com/casbin/casbin) on [Echo](https://github.com/labstack/echo) web framework. Simplify your authorization with powerful role-based access control.\n\n## ✨ Features\n\n- 🚀 **Easy Integration** - Seamlessly integrate with Echo applications\n- 🔒 **RESTful Authorization** - Built for RESTful API security\n- 🛡️ **Token-Based Authentication** - JWT token support out of the box\n- 🔌 **Flexible Data Source** - Define your own data source interface\n- ⚡ **High Performance** - Minimal overhead middleware\n- 🎯 **Role-Based Access Control** - Fine-grained RBAC support\n\n## 📦 Installation\n\n```shell\ngo get github.com/prongbang/casbinrest\n```\n\n## 🚀 Quick Start\n\n### 1. Create Your Data Source\n\nImplement the `DataSource` interface to fetch roles based on tokens:\n\n```go\ntype redisDataSource struct {\n    // Add your Redis client here\n}\n\nfunc NewRedisDataSource() casbinrest.DataSource {\n    return \u0026redisDataSource{}\n}\n\nfunc (r *redisDataSource) GetRoleByToken(reqToken string) string {\n    // Implement your logic to fetch role from Redis\n    // This is just a simple example\n    if reqToken == \"valid-admin-token\" {\n        return \"admin\"\n    }\n    return \"anonymous\"\n}\n```\n\n### 2. Setup Casbin and Echo\n\n```go\npackage main\n\nimport (\n    \"github.com/labstack/echo/v4\"\n    \"github.com/prongbang/casbinrest\"\n    \"github.com/casbin/casbin/v2\"\n    \"net/http\"\n)\n\nfunc main() {\n    // Initialize data source\n    redisSource := NewRedisDataSource()\n    \n    // Setup Casbin enforcer\n    ce, _ := casbin.NewEnforcer(\"auth_model.conf\", \"policy.csv\")\n    \n    // Create Echo instance\n    e := echo.New()\n    \n    // Apply middleware\n    e.Use(casbinrest.Middleware(ce, redisSource))\n    \n    // Routes\n    e.GET(\"/\", func(c echo.Context) error {\n        return c.JSON(http.StatusOK, \"Welcome!\")\n    })\n    \n    e.GET(\"/admin\", func(c echo.Context) error {\n        return c.JSON(http.StatusOK, \"Admin area\")\n    })\n    \n    e.GET(\"/login\", func(c echo.Context) error {\n        return c.JSON(http.StatusOK, \"Login page\")\n    })\n    \n    e.Logger.Fatal(e.Start(\":1323\"))\n}\n```\n\n## ⚙️ Configuration\n\n### Casbin Model Configuration\n\nCreate `auth_model.conf`:\n\n```ini\n[request_definition]\nr = sub, obj, act\n\n[policy_definition]\np = sub, obj, act\n\n[policy_effect]\ne = some(where (p.eft == allow))\n\n[matchers]\nm = r.sub == p.sub \u0026\u0026 keyMatch(r.obj, p.obj) \u0026\u0026 regexMatch(r.act, p.act)\n```\n\n### Policy Definition\n\nCreate `policy.csv`:\n\n```csv\np, admin, /, GET\np, admin, /admin, GET\np, anonymous, /login, GET\np, anonymous, /, GET\n```\n\n## 🔍 Usage Examples\n\n### Making Requests\n\n```shell\n# Access public endpoint\ncurl http://localhost:1323/login\n\n# Access protected endpoint without token\ncurl http://localhost:1323/admin\n# Returns 403 Forbidden\n\n# Access protected endpoint with valid token\ncurl -H \"Authorization: Bearer your-admin-token\" http://localhost:1323/admin\n# Returns 200 OK\n```\n\n### Custom Data Sources\n\nImplement different data sources for various backends:\n\n```go\n// MySQL Data Source\ntype mysqlDataSource struct {\n    db *sql.DB\n}\n\nfunc (m *mysqlDataSource) GetRoleByToken(token string) string {\n    var role string\n    err := m.db.QueryRow(\"SELECT role FROM users WHERE token = ?\", token).Scan(\u0026role)\n    if err != nil {\n        return \"anonymous\"\n    }\n    return role\n}\n\n// MongoDB Data Source\ntype mongoDataSource struct {\n    collection *mongo.Collection\n}\n\nfunc (m *mongoDataSource) GetRoleByToken(token string) string {\n    var result struct {\n        Role string `bson:\"role\"`\n    }\n    err := m.collection.FindOne(context.Background(), bson.M{\"token\": token}).Decode(\u0026result)\n    if err != nil {\n        return \"anonymous\"\n    }\n    return result.Role\n}\n```\n\n## 🔐 Security Best Practices\n\n1. **Use Secure Tokens** - Always use properly signed JWT tokens\n2. **HTTPS Only** - Ensure your API is served over HTTPS\n3. **Token Expiration** - Implement token expiration mechanisms\n4. **Regular Policy Updates** - Keep your policies up to date\n5. **Audit Logging** - Log authorization decisions for security audits\n\n## 📊 Performance Considerations\n\n- The middleware has minimal overhead\n- Policy matching is efficient with Casbin's optimized algorithms\n- Consider caching role lookups for high-traffic applications\n- Use appropriate indexes in your data source\n\n## 🤝 Contributing\n\nContributions are welcome! Please feel free to submit a Pull Request.\n\n## 📄 License\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\n\n## 💖 Support the Project\n\nIf you find this package helpful, please consider supporting it:\n\n[![\"Buy Me A Coffee\"](https://www.buymeacoffee.com/assets/img/custom_images/orange_img.png)](https://www.buymeacoffee.com/prongbang)\n\n## 🔗 Related Projects\n\n- [Casbin](https://github.com/casbin/casbin) - Authorization library\n- [Echo](https://github.com/labstack/echo) - High performance Go web framework\n- [JWT-Go](https://github.com/golang-jwt/jwt) - JWT implementation for Go\n\n---\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fprongbang%2Fcasbinrest","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fprongbang%2Fcasbinrest","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fprongbang%2Fcasbinrest/lists"}