fastapi-authz


Namefastapi-authz JSON
Version 1.0.0 PyPI version JSON
download
home_pagehttps://github.com/pycasbin/fastapi-authz
SummaryAn authorization middleware for FastAPI that supports ACL, RBAC, ABAC, based on PyCasbin
upload_time2024-03-29 10:54:47
maintainerNone
docs_urlNone
authorZxilly
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 casbin fastapi
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # fastapi-authz

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

fastapi-authz 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-authz
```

Clone this repo

```bash
git clone https://github.com/pycasbin/fastapi-authz.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_authz 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-authz 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/pycasbin/fastapi-authz",
    "name": "fastapi-authz",
    "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": "Zxilly",
    "author_email": "zhouxinyu1001@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/63/6b/92f34fa9aaf9916cf767a8edd813435b81d15affd05e003670635ff59ca4/fastapi-authz-1.0.0.tar.gz",
    "platform": null,
    "description": "# fastapi-authz\n\n[![Build Status](https://github.com/pycasbin/fastapi-authz/actions/workflows/release.yml/badge.svg)](https://github.com/pycasbin/fastapi-authz/actions/workflows/release.yml)\n[![Coverage Status](https://coveralls.io/repos/github/pycasbin/fastapi-authz/badge.svg)](https://coveralls.io/github/pycasbin/fastapi-authz)\n[![Version](https://img.shields.io/pypi/v/fastapi-authz.svg)](https://pypi.org/project/fastapi-authz/)\n[![PyPI - Wheel](https://img.shields.io/pypi/wheel/fastapi-authz.svg)](https://pypi.org/project/fastapi-authz/)\n[![Pyversions](https://img.shields.io/pypi/pyversions/fastapi-authz.svg)](https://pypi.org/project/fastapi-authz/)\n[![Download](https://img.shields.io/pypi/dm/fastapi-authz.svg)](https://pypi.org/project/fastapi-authz/)\n[![Discord](https://img.shields.io/discord/1022748306096537660?logo=discord&label=discord&color=5865F2)](https://discord.gg/S5UjpzGZjN)\n\nfastapi-authz is an authorization middleware for [FastAPI](https://fastapi.tiangolo.com/), it's based\non [PyCasbin](https://github.com/casbin/pycasbin).\n\n## Installation\n\nInstall from pip\n\n```bash\npip install fastapi-authz\n```\n\nClone this repo\n\n```bash\ngit clone https://github.com/pycasbin/fastapi-authz.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_authz 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-authz 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.0.0",
    "project_urls": {
        "Homepage": "https://github.com/pycasbin/fastapi-authz"
    },
    "split_keywords": [
        "fastapi",
        " starlette",
        " middleware",
        " pycasbin",
        " casbin",
        " auth",
        " authz",
        " acl",
        " rbac",
        " abac",
        " access control",
        " authorization",
        " permission"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "b5ebc8c8d2e83990461881d0d9ae66ad702426fac05e8715d617d069c1fd3ad8",
                "md5": "69a1e35b1bc41528507a10fc0b1fb942",
                "sha256": "e8170604d2a9c487fb69fa4d358580c5b0d6398c2278d68293441117d51d0acf"
            },
            "downloads": -1,
            "filename": "fastapi_authz-1.0.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "69a1e35b1bc41528507a10fc0b1fb942",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.6",
            "size": 10816,
            "upload_time": "2024-03-29T10:54:46",
            "upload_time_iso_8601": "2024-03-29T10:54:46.432730Z",
            "url": "https://files.pythonhosted.org/packages/b5/eb/c8c8d2e83990461881d0d9ae66ad702426fac05e8715d617d069c1fd3ad8/fastapi_authz-1.0.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "636b92f34fa9aaf9916cf767a8edd813435b81d15affd05e003670635ff59ca4",
                "md5": "40098f18758c0d5131bca3c0db97e380",
                "sha256": "d022cefc8ec93e43d98825bafcc4ea145636b79a072bda2fc95b1051f19f608e"
            },
            "downloads": -1,
            "filename": "fastapi-authz-1.0.0.tar.gz",
            "has_sig": false,
            "md5_digest": "40098f18758c0d5131bca3c0db97e380",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.6",
            "size": 8920,
            "upload_time": "2024-03-29T10:54:47",
            "upload_time_iso_8601": "2024-03-29T10:54:47.970839Z",
            "url": "https://files.pythonhosted.org/packages/63/6b/92f34fa9aaf9916cf767a8edd813435b81d15affd05e003670635ff59ca4/fastapi-authz-1.0.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-03-29 10:54:47",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "pycasbin",
    "github_project": "fastapi-authz",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "requirements": [
        {
            "name": "casbin",
            "specs": []
        },
        {
            "name": "fastapi",
            "specs": []
        }
    ],
    "lcname": "fastapi-authz"
}
        
Elapsed time: 0.21592s