Mux-authz is an authorization middleware for Mux, it’s based on Casbin. If you have better suggestions, please submit the issue.
go get github.com/casbin/mux-authz
This repo is based on Casbin, so you need to prepare two files in advance.
The Casbin model file describes access control models like ACL, RBAC, ABAC, etc.
The Casbin policy file describes the authorization policy rules.
For how to write these files, please refer to: https://github.com/casbin/casbin#get-started
-
Create your Casbin model file authz_model.conf and Casbin policy file authz_policy.csv into this folder.
-
Load model and policy
c := new(authz.CasbinAuthorizer) err :=c.Load("authz_model.conf", "authz_policy.csv") if err != nil { fmt.Println(err.Error()) }
-
Use Middleware
r :=mux.NewRouter() r.HandleFunc("/{url:[A-Za-z0-9\\/]+}", handler) r.Use(c.Middleware)
Note: Now we only support check the whole path. So we recommend using path with regular expressions in the HandleFunc(). In this way, you don't have to worry about 404 due to the number of ‘/‘.For example
/book1/1
and/bookshelf1/book1/1
.
If you have any questions, you can refer to mux-authz_test.go.
package main
import (
"fmt"
authz "github.com/casbin/mux-authz"
"github.com/gorilla/mux"
"log"
"net/http"
)
func main() {
c := new(authz.CasbinAuthorizer)
err :=c.Load("authz_model.conf", "authz_policy.csv")
if err != nil {
fmt.Println(err.Error())
}
// A very simple health check handler.
handler := http.HandlerFunc(func (w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
})
r :=mux.NewRouter()
r.HandleFunc("/{url:[A-Za-z0-9\\/]+}", handler)
r.Use(c.Middleware)
log.Fatal(http.ListenAndServe(":8080",r))
}
Note: This plugin only supports HTTP basic authentication to get the logged-in user name, if you use other kinds of authentication like OAuth, LDAP, etc, you may need to customize this plugin.
The authorization determines a request based on {subject, object, action}
, which means what subject
can perform what action
on what object
. In this plugin, the meanings are:
subject
: the logged-on user nameobject
: the URL path for the web resource like "dataset1/item1"action
: HTTP method like GET, POST, PUT, DELETE, or the high-level actions you defined like "read-file", "write-blog"
For how to write authorization policy and other details, please refer to the Casbin's documentation.