fastapi-casbin-auth


Namefastapi-casbin-auth JSON
Version 1.4.0 PyPI version JSON
download
home_pagehttps://github.com/officialpycasbin/fastapi-casbin-auth
SummaryAn authorization middleware for FastAPI that supports ACL, RBAC, ABAC, based on PyCasbin
upload_time2025-08-13 05:44:42
maintainerNone
docs_urlNone
authorCasbin
requires_python>=3.6
licenseApache 2.0
keywords fastapi starlette middleware pycasbin casbin auth authz acl rbac abac access control authorization permission
VCS
bugtrack_url
requirements annotated-types anyio exceptiongroup fastapi idna pycasbin pydantic pydantic-core simpleeval sniffio starlette typing-extensions typing-inspection
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # fastapi-casbin-auth

[![Build Status](https://github.com/officialpycasbin/fastapi-casbin-auth/actions/workflows/release.yml/badge.svg)](https://github.com/officialpycasbin/fastapi-casbin-auth/actions/workflows/release.yml)
[![Coverage Status](https://coveralls.io/repos/github/officialpycasbin/fastapi-casbin-auth/badge.svg)](https://coveralls.io/github/officialpycasbin/fastapi-casbin-auth)
[![Version](https://img.shields.io/pypi/v/fastapi-casbin-auth.svg)](https://pypi.org/project/fastapi-casbin-auth/)
[![PyPI - Wheel](https://img.shields.io/pypi/wheel/fastapi-casbin-auth.svg)](https://pypi.org/project/fastapi-casbin-auth/)
[![Pyversions](https://img.shields.io/pypi/pyversions/fastapi-casbin-auth.svg)](https://pypi.org/project/fastapi-casbin-auth/)
[![Download](https://static.pepy.tech/badge/fastapi-casbin-auth)](https://pypi.org/project/fastapi-casbin-auth/)
[![Discord](https://img.shields.io/discord/1022748306096537660?logo=discord&label=discord&color=5865F2)](https://discord.gg/S5UjpzGZjN)

fastapi-casbin-auth is an authorization middleware for [FastAPI](https://fastapi.tiangolo.com/), it's based on [PyCasbin](https://github.com/casbin/pycasbin).

## Installation

Install from pip

```bash
pip install fastapi-casbin-auth
```

Clone this repo

```bash
git clone https://github.com/officialpycasbin/fastapi-casbin-auth.git
python setup.py install
```

## Quickstart

This middleware is designed to work with another middleware which implement `AuthenticationMiddleware` interface.

```python
import base64
import binascii

import casbin

from fastapi import FastAPI
from starlette.authentication import AuthenticationBackend, AuthenticationError, SimpleUser, AuthCredentials
from starlette.middleware.authentication import AuthenticationMiddleware

from fastapi_casbin_auth import CasbinMiddleware

app = FastAPI()


class BasicAuth(AuthenticationBackend):
    async def authenticate(self, request):
        if "Authorization" not in request.headers:
            return None

        auth = request.headers["Authorization"]
        try:
            scheme, credentials = auth.split()
            decoded = base64.b64decode(credentials).decode("ascii")
        except (ValueError, UnicodeDecodeError, binascii.Error):
            raise AuthenticationError("Invalid basic auth credentials")

        username, _, password = decoded.partition(":")
        return AuthCredentials(["authenticated"]), SimpleUser(username)


enforcer = casbin.Enforcer('../examples/rbac_model.conf', '../examples/rbac_policy.csv')

app.add_middleware(CasbinMiddleware, enforcer=enforcer)
app.add_middleware(AuthenticationMiddleware, backend=BasicAuth())


@app.get('/')
async def index():
    return "If you see this, you have been authenticated."


@app.get('/dataset1/protected')
async def auth_test():
    return "You must be alice to see this."
```

- anonymous request

```bash
curl -i http://127.0.0.1:8000/dataset1/protected
```

```bash
HTTP/1.1 403 Forbidden
date: Mon, 01 Mar 2021 09:00:08 GMT
server: uvicorn
content-length: 11
content-type: application/json

"Forbidden"
```

- authenticated request

```bash
curl -i -u alice:password http://127.0.0.1:8000/dataset1/protected
```

```bash
HTTP/1.1 200 OK
date: Mon, 01 Mar 2021 09:04:54 GMT
server: uvicorn
content-length: 32
content-type: application/json

"You must be alice to see this."
```

It used the casbin config from `examples` folder, and you can find this demo in `demo` folder.

You can also view the unit tests to understand this middleware.

Besides, there is another example for `CasbinMiddleware` which is designed to work with JWT authentication. You can find
it in `demo/jwt_test.py`.

## Development

### Run unit tests

1. Fork/Clone repository
2. Install fastapi-casbin-auth dependencies, and run `pytest`

```bash
pip install -r dev_requirements.txt
pip install -r requirements.txt
pytest
```

### Update requirements with pip-tools

```bash
# update requirements.txt
pip-compile --no-annotate --no-header --rebuild requirements.in
# sync venv
pip-sync
```

### Manually Bump Version

```
bumpversion major  # major release
or
bumpversion minor  # minor release
or
bumpversion patch  # hotfix release
```

## 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" (currently no official support in this middleware)

For how to write authorization policy and other details, please refer
to [the Casbin's documentation](https://casbin.org).

## Getting Help

- [Casbin](https://casbin.org)

## License

This project is under Apache 2.0 License. See the [LICENSE](LICENSE) file for the full license text.

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/officialpycasbin/fastapi-casbin-auth",
    "name": "fastapi-casbin-auth",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.6",
    "maintainer_email": null,
    "keywords": "fastapi, starlette, middleware, pycasbin, casbin, auth, authz, acl, rbac, abac, access control, authorization, permission",
    "author": "Casbin",
    "author_email": "admin@casbin.org",
    "download_url": "https://files.pythonhosted.org/packages/72/6f/24b451db8149365d3e6ee73ced32533bff796602b761ff90474808c5085b/fastapi_casbin_auth-1.4.0.tar.gz",
    "platform": null,
    "description": "# fastapi-casbin-auth\n\n[![Build Status](https://github.com/officialpycasbin/fastapi-casbin-auth/actions/workflows/release.yml/badge.svg)](https://github.com/officialpycasbin/fastapi-casbin-auth/actions/workflows/release.yml)\n[![Coverage Status](https://coveralls.io/repos/github/officialpycasbin/fastapi-casbin-auth/badge.svg)](https://coveralls.io/github/officialpycasbin/fastapi-casbin-auth)\n[![Version](https://img.shields.io/pypi/v/fastapi-casbin-auth.svg)](https://pypi.org/project/fastapi-casbin-auth/)\n[![PyPI - Wheel](https://img.shields.io/pypi/wheel/fastapi-casbin-auth.svg)](https://pypi.org/project/fastapi-casbin-auth/)\n[![Pyversions](https://img.shields.io/pypi/pyversions/fastapi-casbin-auth.svg)](https://pypi.org/project/fastapi-casbin-auth/)\n[![Download](https://static.pepy.tech/badge/fastapi-casbin-auth)](https://pypi.org/project/fastapi-casbin-auth/)\n[![Discord](https://img.shields.io/discord/1022748306096537660?logo=discord&label=discord&color=5865F2)](https://discord.gg/S5UjpzGZjN)\n\nfastapi-casbin-auth is an authorization middleware for [FastAPI](https://fastapi.tiangolo.com/), it's based on [PyCasbin](https://github.com/casbin/pycasbin).\n\n## Installation\n\nInstall from pip\n\n```bash\npip install fastapi-casbin-auth\n```\n\nClone this repo\n\n```bash\ngit clone https://github.com/officialpycasbin/fastapi-casbin-auth.git\npython setup.py install\n```\n\n## Quickstart\n\nThis middleware is designed to work with another middleware which implement `AuthenticationMiddleware` interface.\n\n```python\nimport base64\nimport binascii\n\nimport casbin\n\nfrom fastapi import FastAPI\nfrom starlette.authentication import AuthenticationBackend, AuthenticationError, SimpleUser, AuthCredentials\nfrom starlette.middleware.authentication import AuthenticationMiddleware\n\nfrom fastapi_casbin_auth import CasbinMiddleware\n\napp = FastAPI()\n\n\nclass BasicAuth(AuthenticationBackend):\n    async def authenticate(self, request):\n        if \"Authorization\" not in request.headers:\n            return None\n\n        auth = request.headers[\"Authorization\"]\n        try:\n            scheme, credentials = auth.split()\n            decoded = base64.b64decode(credentials).decode(\"ascii\")\n        except (ValueError, UnicodeDecodeError, binascii.Error):\n            raise AuthenticationError(\"Invalid basic auth credentials\")\n\n        username, _, password = decoded.partition(\":\")\n        return AuthCredentials([\"authenticated\"]), SimpleUser(username)\n\n\nenforcer = casbin.Enforcer('../examples/rbac_model.conf', '../examples/rbac_policy.csv')\n\napp.add_middleware(CasbinMiddleware, enforcer=enforcer)\napp.add_middleware(AuthenticationMiddleware, backend=BasicAuth())\n\n\n@app.get('/')\nasync def index():\n    return \"If you see this, you have been authenticated.\"\n\n\n@app.get('/dataset1/protected')\nasync def auth_test():\n    return \"You must be alice to see this.\"\n```\n\n- anonymous request\n\n```bash\ncurl -i http://127.0.0.1:8000/dataset1/protected\n```\n\n```bash\nHTTP/1.1 403 Forbidden\ndate: Mon, 01 Mar 2021 09:00:08 GMT\nserver: uvicorn\ncontent-length: 11\ncontent-type: application/json\n\n\"Forbidden\"\n```\n\n- authenticated request\n\n```bash\ncurl -i -u alice:password http://127.0.0.1:8000/dataset1/protected\n```\n\n```bash\nHTTP/1.1 200 OK\ndate: Mon, 01 Mar 2021 09:04:54 GMT\nserver: uvicorn\ncontent-length: 32\ncontent-type: application/json\n\n\"You must be alice to see this.\"\n```\n\nIt used the casbin config from `examples` folder, and you can find this demo in `demo` folder.\n\nYou can also view the unit tests to understand this middleware.\n\nBesides, there is another example for `CasbinMiddleware` which is designed to work with JWT authentication. You can find\nit in `demo/jwt_test.py`.\n\n## Development\n\n### Run unit tests\n\n1. Fork/Clone repository\n2. Install fastapi-casbin-auth dependencies, and run `pytest`\n\n```bash\npip install -r dev_requirements.txt\npip install -r requirements.txt\npytest\n```\n\n### Update requirements with pip-tools\n\n```bash\n# update requirements.txt\npip-compile --no-annotate --no-header --rebuild requirements.in\n# sync venv\npip-sync\n```\n\n### Manually Bump Version\n\n```\nbumpversion major  # major release\nor\nbumpversion minor  # minor release\nor\nbumpversion patch  # hotfix release\n```\n\n## Documentation\n\nThe authorization determines a request based on ``{subject, object, action}``, which means what ``subject`` can perform\nwhat ``action`` on what ``object``. In this plugin, the meanings are:\n\n1. ``subject``: the logged-in user name\n2. ``object``: the URL path for the web resource like `dataset1/item1`\n3. ``action``: HTTP method like GET, POST, PUT, DELETE, or the high-level actions you defined like \"read-file\", \"\n   write-blog\" (currently no official support in this middleware)\n\nFor how to write authorization policy and other details, please refer\nto [the Casbin's documentation](https://casbin.org).\n\n## Getting Help\n\n- [Casbin](https://casbin.org)\n\n## License\n\nThis project is under Apache 2.0 License. See the [LICENSE](LICENSE) file for the full license text.\n",
    "bugtrack_url": null,
    "license": "Apache 2.0",
    "summary": "An authorization middleware for FastAPI that supports ACL, RBAC, ABAC, based on PyCasbin",
    "version": "1.4.0",
    "project_urls": {
        "Homepage": "https://github.com/officialpycasbin/fastapi-casbin-auth"
    },
    "split_keywords": [
        "fastapi",
        " starlette",
        " middleware",
        " pycasbin",
        " casbin",
        " auth",
        " authz",
        " acl",
        " rbac",
        " abac",
        " access control",
        " authorization",
        " permission"
    ],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "c03c79a138267077f0b607eae571431e0dbbf440f5e37faf6e89008704d95917",
                "md5": "0997c869861a546146edf03409d1696d",
                "sha256": "03751a52d8295916b1dd79f247b1e12c5ff422bb46ff5591816872b801905489"
            },
            "downloads": -1,
            "filename": "fastapi_casbin_auth-1.4.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "0997c869861a546146edf03409d1696d",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.6",
            "size": 11498,
            "upload_time": "2025-08-13T05:44:41",
            "upload_time_iso_8601": "2025-08-13T05:44:41.036108Z",
            "url": "https://files.pythonhosted.org/packages/c0/3c/79a138267077f0b607eae571431e0dbbf440f5e37faf6e89008704d95917/fastapi_casbin_auth-1.4.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "726f24b451db8149365d3e6ee73ced32533bff796602b761ff90474808c5085b",
                "md5": "64739f503f74e3e98a057eb5a66fc5e9",
                "sha256": "e1088bc1afa457bc2b125a99bbd32c23095fac2887211e596ca438fe99329206"
            },
            "downloads": -1,
            "filename": "fastapi_casbin_auth-1.4.0.tar.gz",
            "has_sig": false,
            "md5_digest": "64739f503f74e3e98a057eb5a66fc5e9",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.6",
            "size": 9439,
            "upload_time": "2025-08-13T05:44:42",
            "upload_time_iso_8601": "2025-08-13T05:44:42.168250Z",
            "url": "https://files.pythonhosted.org/packages/72/6f/24b451db8149365d3e6ee73ced32533bff796602b761ff90474808c5085b/fastapi_casbin_auth-1.4.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-08-13 05:44:42",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "officialpycasbin",
    "github_project": "fastapi-casbin-auth",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "requirements": [
        {
            "name": "annotated-types",
            "specs": [
                [
                    "==",
                    "0.7.0"
                ]
            ]
        },
        {
            "name": "anyio",
            "specs": [
                [
                    "==",
                    "4.10.0"
                ]
            ]
        },
        {
            "name": "exceptiongroup",
            "specs": [
                [
                    "==",
                    "1.3.0"
                ]
            ]
        },
        {
            "name": "fastapi",
            "specs": [
                [
                    "==",
                    "0.116.1"
                ]
            ]
        },
        {
            "name": "idna",
            "specs": [
                [
                    "==",
                    "3.10"
                ]
            ]
        },
        {
            "name": "pycasbin",
            "specs": [
                [
                    "==",
                    "2.0.0"
                ]
            ]
        },
        {
            "name": "pydantic",
            "specs": [
                [
                    "==",
                    "2.11.7"
                ]
            ]
        },
        {
            "name": "pydantic-core",
            "specs": [
                [
                    "==",
                    "2.33.2"
                ]
            ]
        },
        {
            "name": "simpleeval",
            "specs": [
                [
                    "==",
                    "1.0.3"
                ]
            ]
        },
        {
            "name": "sniffio",
            "specs": [
                [
                    "==",
                    "1.3.1"
                ]
            ]
        },
        {
            "name": "starlette",
            "specs": [
                [
                    "==",
                    "0.47.2"
                ]
            ]
        },
        {
            "name": "typing-extensions",
            "specs": [
                [
                    "==",
                    "4.14.1"
                ]
            ]
        },
        {
            "name": "typing-inspection",
            "specs": [
                [
                    "==",
                    "0.4.1"
                ]
            ]
        }
    ],
    "lcname": "fastapi-casbin-auth"
}
        
Elapsed time: 4.73221s