{"id":22959850,"url":"https://github.com/pycasbin/fastapi-authz","last_synced_at":"2025-04-05T09:04:57.211Z","repository":{"id":37439681,"uuid":"341539184","full_name":"pycasbin/fastapi-authz","owner":"pycasbin","description":"Use Casbin in FastAPI, Casbin is a powerful and efficient open-source access control library.","archived":false,"fork":false,"pushed_at":"2024-03-29T10:54:45.000Z","size":44,"stargazers_count":172,"open_issues_count":1,"forks_count":17,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-03-28T14:40:30.949Z","etag":null,"topics":["abac","access-control","acl","auth","authoization","authz","casbin","fastapi","rbac"],"latest_commit_sha":null,"homepage":"https://github.com/casbin/pycasbin","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/pycasbin.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2021-02-23T11:56:34.000Z","updated_at":"2025-03-18T19:15:19.000Z","dependencies_parsed_at":"2024-06-21T14:53:45.924Z","dependency_job_id":null,"html_url":"https://github.com/pycasbin/fastapi-authz","commit_stats":{"total_commits":34,"total_committers":5,"mean_commits":6.8,"dds":0.3529411764705882,"last_synced_commit":"b809e72db587351be9a29102512a573d3f0e8f06"},"previous_names":[],"tags_count":9,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pycasbin%2Ffastapi-authz","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pycasbin%2Ffastapi-authz/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pycasbin%2Ffastapi-authz/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pycasbin%2Ffastapi-authz/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/pycasbin","download_url":"https://codeload.github.com/pycasbin/fastapi-authz/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247312077,"owners_count":20918344,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["abac","access-control","acl","auth","authoization","authz","casbin","fastapi","rbac"],"created_at":"2024-12-14T18:29:00.598Z","updated_at":"2025-04-05T09:04:57.161Z","avatar_url":"https://github.com/pycasbin.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# 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\u0026label=discord\u0026color=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","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpycasbin%2Ffastapi-authz","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fpycasbin%2Ffastapi-authz","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpycasbin%2Ffastapi-authz/lists"}