# 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://img.shields.io/pypi/dm/fastapi-casbin-auth.svg)](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/2d/70/c023a165d83aab3b0d9253f8a70979e9aa671ef49b94fdf7050da3e42f01/fastapi_casbin_auth-1.2.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://img.shields.io/pypi/dm/fastapi-casbin-auth.svg)](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.2.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": "",
"digests": {
"blake2b_256": "0e95f915de6d877cbe8608fe41f55ea796ccbab5f61869819356bfed5d5711f8",
"md5": "bc1b09d21510805e3fc293fc73d0e125",
"sha256": "3d9a1b5509ef49bdae0be202277236a450adcd6d9d72096f160c42ab76388a79"
},
"downloads": -1,
"filename": "fastapi_casbin_auth-1.2.0-py3-none-any.whl",
"has_sig": false,
"md5_digest": "bc1b09d21510805e3fc293fc73d0e125",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.6",
"size": 10940,
"upload_time": "2024-11-12T02:32:52",
"upload_time_iso_8601": "2024-11-12T02:32:52.857625Z",
"url": "https://files.pythonhosted.org/packages/0e/95/f915de6d877cbe8608fe41f55ea796ccbab5f61869819356bfed5d5711f8/fastapi_casbin_auth-1.2.0-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "2d70c023a165d83aab3b0d9253f8a70979e9aa671ef49b94fdf7050da3e42f01",
"md5": "0f0455968c7a06480bac2efa914cbeeb",
"sha256": "81370162d60364d56b7f345c276c10f15d8c131f89c96db19864f73bfa395aee"
},
"downloads": -1,
"filename": "fastapi_casbin_auth-1.2.0.tar.gz",
"has_sig": false,
"md5_digest": "0f0455968c7a06480bac2efa914cbeeb",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.6",
"size": 8931,
"upload_time": "2024-11-12T02:32:54",
"upload_time_iso_8601": "2024-11-12T02:32:54.193149Z",
"url": "https://files.pythonhosted.org/packages/2d/70/c023a165d83aab3b0d9253f8a70979e9aa671ef49b94fdf7050da3e42f01/fastapi_casbin_auth-1.2.0.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2024-11-12 02:32:54",
"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": [],
"lcname": "fastapi-casbin-auth"
}