{"id":20035817,"url":"https://github.com/officialpycasbin/fastapi-casbin-auth","last_synced_at":"2025-06-29T17:03:40.587Z","repository":{"id":262363235,"uuid":"887007417","full_name":"officialpycasbin/fastapi-casbin-auth","owner":"officialpycasbin","description":"FastAPI authorization middleware based on PyCasbin","archived":false,"fork":false,"pushed_at":"2024-11-12T02:32:52.000Z","size":41,"stargazers_count":6,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-04-03T04:23:03.513Z","etag":null,"topics":["abac","acl","auth","authorization","casbin","fastapi","middleware","py","pycasbin","python","pythonweb","rbac","web"],"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/officialpycasbin.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":"2024-11-12T02:16:22.000Z","updated_at":"2025-04-02T10:58:12.000Z","dependencies_parsed_at":"2024-11-12T03:23:03.698Z","dependency_job_id":"47d937a5-e52d-4d41-bbfc-29a30d054590","html_url":"https://github.com/officialpycasbin/fastapi-casbin-auth","commit_stats":null,"previous_names":["officialpycasbin/fastapi-authz"],"tags_count":11,"template":false,"template_full_name":null,"purl":"pkg:github/officialpycasbin/fastapi-casbin-auth","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/officialpycasbin%2Ffastapi-casbin-auth","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/officialpycasbin%2Ffastapi-casbin-auth/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/officialpycasbin%2Ffastapi-casbin-auth/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/officialpycasbin%2Ffastapi-casbin-auth/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/officialpycasbin","download_url":"https://codeload.github.com/officialpycasbin/fastapi-casbin-auth/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/officialpycasbin%2Ffastapi-casbin-auth/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":262632323,"owners_count":23340212,"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","acl","auth","authorization","casbin","fastapi","middleware","py","pycasbin","python","pythonweb","rbac","web"],"created_at":"2024-11-13T10:09:22.294Z","updated_at":"2025-06-29T17:03:40.552Z","avatar_url":"https://github.com/officialpycasbin.png","language":"Python","funding_links":[],"categories":["Python","Third-Party Extensions"],"sub_categories":["Auth"],"readme":"# 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\u0026label=discord\u0026color=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","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fofficialpycasbin%2Ffastapi-casbin-auth","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fofficialpycasbin%2Ffastapi-casbin-auth","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fofficialpycasbin%2Ffastapi-casbin-auth/lists"}