Redis Adapter is the Redis adapter for Casbin. With this library, Casbin can load policy from Redis or save policy to it.
go get github.com/casbin/redis-adapter/v3
The Config
struct supports the following options:
Network
(string): Network type, e.g., "tcp", "unix" (required when not using Pool)Address
(string): Redis server address, e.g., "127.0.0.1:6379" (required when not using Pool)Key
(string): Redis key to store Casbin rules (default: "casbin_rules")Username
(string): Username for Redis authentication (optional)Password
(string): Password for Redis authentication (optional)TLSConfig
(*tls.Config): TLS configuration for secure connections (optional)Pool
(*redis.Pool): Existing Redis connection pool (optional, if provided, other connection options are ignored)
package main
import (
"github.com/casbin/casbin/v2"
"github.com/casbin/redis-adapter/v3"
)
func main() {
// Recommended approach using Config
config := &redisadapter.Config{Network: "tcp", Address: "127.0.0.1:6379"}
a, _ := redisadapter.NewAdapter(config)
// With password authentication
// config := &redisadapter.Config{Network: "tcp", Address: "127.0.0.1:6379", Password: "123"}
// a, _ := redisadapter.NewAdapter(config)
// With user credentials
// config := &redisadapter.Config{Network: "tcp", Address: "127.0.0.1:6379", Username: "user", Password: "pass"}
// a, _ := redisadapter.NewAdapter(config)
// With TLS configuration
// var clientTLSConfig tls.Config
// ...
// config := &redisadapter.Config{Network: "tcp", Address: "127.0.0.1:6379", Username: "testAccount", Password: "123456", TLSConfig: &clientTLSConfig}
// a, _ := redisadapter.NewAdapter(config)
e, _ := casbin.NewEnforcer("examples/rbac_model.conf", a)
// Load the policy from DB.
e.LoadPolicy()
// Check the permission.
e.Enforce("alice", "data1", "read")
// Modify the policy.
// e.AddPolicy(...)
// e.RemovePolicy(...)
// Save the policy back to DB.
e.SavePolicy()
}
package main
import (
"github.com/casbin/casbin/v2"
"github.com/casbin/redis-adapter/v3"
"github.com/gomodule/redigo/redis"
)
func main() {
pool := &redis.Pool{Dial: func() (redis.Conn, error) { return redis.Dial("tcp", "127.0.0.1:6379") }}
config := &redisadapter.Config{Pool: pool, Key: "casbin_rules"}
a, _ := redisadapter.NewAdapter(config)
e, _ := casbin.NewEnforcer("examples/rbac_model.conf", a)
// Load the policy from DB.
e.LoadPolicy()
// Check the permission.
e.Enforce("alice", "data1", "read")
// Save the policy back to DB.
e.SavePolicy()
}
This project is under Apache 2.0 License. See the LICENSE file for the full license text.