Skip to content

Instantly share code, notes, and snippets.

@stefanwuthrich
Created November 21, 2017 06:01
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save stefanwuthrich/c56e0339a95bc08715a1c2db76a9a986 to your computer and use it in GitHub Desktop.
Save stefanwuthrich/c56e0339a95bc08715a1c2db76a9a986 to your computer and use it in GitHub Desktop.
Casbin Authorization for qiangxue/golang-restful-starter-kit
package util
import (
"net/http"
"github.com/casbin/casbin"
"github.com/qiangxue/golang-restful-starter-kit/app"
"github.com/go-ozzo/ozzo-routing"
)
// Authorizer is a middleware that controls the access to the HTTP service, it is based
// on Casbin, which supports access control models like ACL, RBAC, ABAC.
// The plugin determines whether to allow a request based on (user, path, method).
// user: the authenticated user name.
// path: the URL for the requested resource.
// method: one of HTTP methods like GET, POST, PUT, DELETE.
//
// This middleware should be inserted fairly early in the middleware stack to
// protect subsequent layers. All the denied requests will not go further.
//
// It's notable that this middleware should be behind the authentication (e.g.,
// HTTP basic authentication, OAuth), so this plugin can get the logged-in user name
// to perform the authorization.
func Authorizer(e *casbin.Enforcer) routing.Handler {
return func(c *routing.Context) error {
userID:=app.GetRequestScope(c).UserID()
method := c.Request.Method
path := c.Request.URL.Path
if e.Enforce(userID, path, method) {
return nil
} else {
return routing.NewHTTPError(http.StatusUnauthorized, "NOT AUTHORIZED")
}
}
}
@stefanwuthrich
Copy link
Author

casbin conf used:

[request_definition]
r = sub, obj, act

[policy_definition]
p = sub, obj, act

[role_definition]
g = _, _

[policy_effect]
e = some(where (p.eft == allow))

[matchers]
m = g(r.sub, p.sub) && keyMatch(r.obj, p.obj) && (r.act == p.act || p.act == "*")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment