Skip to content

casbin/fasthttp-auth

Repository files navigation

fasthttp-auth

Go Version Build Status Go Report Card License Release Casbin fasthttp

Authorization middleware for fasthttp using Casbin.

Installation

go get github.com/casbin/fasthttp-auth

Quick Start

1. Configuration Files

authz_model.conf:

[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 && r.obj == p.obj && r.act == p.act

authz_policy.csv:

p, alice, /, GET
p, alice, /data1, GET
p, bob, /data2, POST

2. Usage

package main

import (
    "fmt"
    "log"
    "github.com/valyala/fasthttp"
    authz "github.com/casbin/fasthttp-auth"
)

func main() {
    a, err := authz.NewAuthorizerFromFiles("authz_model.conf", "authz_policy.csv")
    if err != nil {
        log.Fatal(err)
    }

    handler := func(ctx *fasthttp.RequestCtx) {
        fmt.Fprintf(ctx, "Welcome!")
    }

    protected := a.Middleware(handler)
    fasthttp.ListenAndServe(":8081", protected)
}

3. Test

# Alice can access / and /data1
curl -H 'X-User: alice' http://localhost:8081/

# Bob can only POST to /data2  
curl -H 'X-User: bob' http://localhost:8081/data2 -X POST

# Anonymous users get 403
curl http://localhost:8081/

How It Works

Authorization is based on {subject, object, action}:

  • Subject: User from X-User header (defaults to anonymous)
  • Object: URL path being accessed
  • Action: HTTP method (GET, POST, etc.)

Examples

See example/main.go for a complete example.

go run ./example

License

Apache-2.0, see LICENSE file

Sponsor this project

 

Packages

No packages published

Contributors 2

  •  
  •  

Languages