chore(release): 1.0.0 [skip ci]

# 1.0.0 (2025-09-16)

### Features

* add initial code ([ea6e3f9](https://github.com/officialpycasbin/sanic-authz/commit/ea6e3f9135a17aa2c9cd00e28bf6bc1a26329e11))
2 files changed
tree: 0a1b6a24418f1c381e6c075f2906bb9dc09495d3
  1. .github/
  2. sanic_authz/
  3. tests/
  4. .coveragerc
  5. .gitignore
  6. .releaserc.json
  7. CHANGELOG.md
  8. dev_requirements.txt
  9. LICENSE
  10. package.json
  11. pyproject.toml
  12. README.md
  13. requirements.in
  14. requirements.txt
README.md

sanic-authz

build Coverage Status Version PyPI - Wheel Pyversions Download Discord

sanic-authz is an authorization middleware for Sanic. It is based on PyCasbin.

Installation

pip install sanic-authz

Module Usage:

import casbin
from sanic import Sanic, response
from sanic.request import Request
from sanic_authz.middleware import CasbinAuthMiddleware

app = Sanic("SanicAuthzExample")
enforcer = casbin.Enforcer("rbac_model.conf", "policy.csv")

# Registration middleware
CasbinAuthMiddleware(sanic_app, enforcer)

# CasbinAuthMiddleware is a global middleware.
# The authorization check will be performed automatically on each request.
# You don't need to manually invoke the middleware in your route handlers.
@app.route("/")
async def homepage(request):
    return response.text("Hello, world!")

Custom subject_getter:

By default, the middleware extracts user identity from the X-User header field. Client requests need to include the X-User header:

curl -H "X-User: alice" http://localhost:8000/data

You can customize the subject_getter to adapt to different authentication mechanisms. For example, JWT authentication:

def jwt_subject_getter(request: Request) -> str:
    token = request.headers.get("Authorization", "").replace("Bearer ", "")
    payload = decode_jwt(token)
    return payload.get("user_id", "anonymous")

CasbinAuthMiddleware(app, enforcer, subject_getter=jwt_subject_getter)

session authentication:

def session_subject_getter(request: Request) -> str:
    return request.ctx.session.get("user_id", "anonymous")

CasbinAuthMiddleware(app, enforcer, subject_getter=session_subject_getter)

Documentation

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:

  1. subject: the logged-in user name
  2. object: the URL path for the web resource like “dataset1/item1”
  3. 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 PyCasbin's documentation.

Getting Help

License

This project is licensed under the Apache 2.0 license.