{"id":17225818,"url":"https://github.com/zopyx/fastapi-auth","last_synced_at":"2025-10-08T01:32:17.942Z","repository":{"id":240531766,"uuid":"802887294","full_name":"zopyx/fastapi-auth","owner":"zopyx","description":"My own authentication system for FastAPI","archived":false,"fork":false,"pushed_at":"2024-07-19T12:52:54.000Z","size":1175,"stargazers_count":5,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-09-12T06:58:55.339Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"wtfpl","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/zopyx.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":"SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-05-19T14:37:59.000Z","updated_at":"2025-04-07T07:12:49.000Z","dependencies_parsed_at":"2024-05-29T21:41:22.143Z","dependency_job_id":null,"html_url":"https://github.com/zopyx/fastapi-auth","commit_stats":null,"previous_names":["zopyx/fastapi-auth"],"tags_count":1,"template":false,"template_full_name":null,"purl":"pkg:github/zopyx/fastapi-auth","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zopyx%2Ffastapi-auth","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zopyx%2Ffastapi-auth/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zopyx%2Ffastapi-auth/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zopyx%2Ffastapi-auth/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/zopyx","download_url":"https://codeload.github.com/zopyx/fastapi-auth/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zopyx%2Ffastapi-auth/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":278519248,"owners_count":26000239,"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","status":"online","status_checked_at":"2025-10-05T02:00:06.059Z","response_time":54,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"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":[],"created_at":"2024-10-15T04:14:33.458Z","updated_at":"2025-10-08T01:32:17.414Z","avatar_url":"https://github.com/zopyx.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# zopyx-fastapi-auth\n\nAn opionated authentication and authorization system for FastAPI.\n\n## Features\n\n- a RDBMS-based user database (support for almost all databases through sqlmodel)\n- a commandline utility for adding, deleting users\n- roles and permissions\n- FastAPI endpoint protection based on permission or roles\n- fully tested, full test coverage, full mypy compliance, parameter checks at runtime\n- a plugin system for arbitrary authentication/authorization (requires one class and one method to implement)\n\n![Tests](https://github.com/zopyx/fastapi-auth/actions/workflows/python-app.yml/badge.svg)\n\n## Status\n\n- in production\n\n## Requirements\n\n- supports Python 3.10-3.12 (no support for Python 3.9 or lower, no support for Python 3.13 yet)\n\n## Example usage\n\n- see `demo_app.py`\n\n## Concepts\n\nThis package is build around the following concepts:\n\n### Roles and permissions\n\nA role is assigned to a user. A user can have one or more roles.  A permission\ndefines a certain certain access scope like `View entries`, `Delete entries`,\n`Update Entries`. A Role can be have multiple permissions. So a  user can have\nmultiple roles and one role can have multiple permissions.\n\nExample on how to define permissions:\n\n```\nfrom fastapi_auth.permissions import Permission\n\nVIEW_PERMISSION = Permission(name=\"view\", description=\"View permission\")\nEDIT_PERMISSION = Permission(name=\"edit\", description=\"Edit permission\")\nDELETE_PERMISSION = Permission(name=\"delete\", description=\"Delete permission\")\n```\n\nRoles are defined this way:\n\n```\nfrom fastapi_auth.permissions import  Role\n\nADMIN_ROLE = Role(\n    name=\"Administrator\",\n    description=\"Admin role\",\n    permissions=[VIEW_PERMISSION, EDIT_PERMISSION, DELETE_PERMISSION],\n)\nUSER_ROLE = Role(\n    name=\"User\",\n    description=\"User role\",\n    permissions=[VIEW_PERMISSION, EDIT_PERMISSION],\n)\nVIEWER_ROLE = Role(\n    name=\"Viewer\",\n    description=\"Viewer role\",\n    permissions=[VIEW_PERMISSION],\n)\n```\n\nAlso, all roles must be registered with a global `ROLES_REGISTRY`:\n\n```\n\nfrom fastapi_auth.roles import ROLES_REGISTRY\n\nROLES_REGISTRY.register(ADMIN_ROLE)\nROLES_REGISTRY.register(USER_ROLE)\nROLES_REGISTRY.register(VIEWER_ROLE)\n```\n\n\nAn endpoint of a FastAPI application be protected through one permission or one\nor more roles.\n\nIn this example, the `/admin` endpoint is only acceessible for an authenticated user with role `Administrator`:\n\n```\n# This is an endpoint that requires the user to be authenticated.  In this case,\n# the user must have the ADMIN_ROLE role.  It is also possible to require a\n# permission instead.  Use the Protected dependency to require authentication.\n# An unauthenticated request as ANONYMOUS_USER will be rejected.\n@app.get(\"/admin\")\ndef admin(user: User = Depends(Protected(required_roles=[ADMIN_ROLE]))):\n    return {\"user\": user}\n```\n\nYou could also protect an endpoint using a permission:\n\n```\n\nfrom fastapi_auth.dependencies import Protected\n\n@app.get(\"/admin\")\ndef admin2(user: User = Depends(Protected(required_permission=VIEW_PERMISSION))):\n    return {\"user\": user}\n\n```\n\nAnother option is to protect a route with a custom callback method returning `True` or `False` for a given\n`Request` and `User`:\n\n```\nfrom fastapi_auth.dependencies import Protected\n\ndef my_check(request: Request, user: User) -\u003e bool:\n    # perform some checks based on request and/or user....\n    return True # or False\n\n@app.get(\"/admin\")\ndef admin3(user: User = Depends(Protected(required_checker=my_check))):\n    return {\"user\": user}\n```\n\nNote that the `user` object passed to the callback is either an already\nauthenticated users or the `ANONYMOUS_USER`.  It is up to the callback to\nauthorize the already authenticated user based on further criteria.\n\n\n\n## Installation of the session middleware\n\nIn order to instrumentize your application, you need call `install_middleware(app)` with your\ncustom FastAPI `app` object.\n\n```\nfrom fastapi_auth.auth_routes import install_middleware\n\n# Your FastAPI app\napp = FastAPI()\n\n# install the session middleware\ninstall_middleware(app)\n\n# add endpoints for authentication examples\napp.mount(\"/auth\", auth_router)\n\n# add static files (for demo login form)\napp.mount(\"/static\", StaticFiles(directory=\"static\"), name=\"static\")\n```\n\n## User management\n\nFor now, `fastapi-auth` stores user accounts inside a SQL database. There is\nthe `fastapi-auth-user-admin` utility for managing user accounts through the\ncommandline.  There is no support (and there will be no support) for managing\nuser accounts through a web admin interface. The database connection can be configured\nusing the `AUTH_DB_URI` environment variable.\n\n### adding user\n\n```\nfastapi-auth-user-admin add \u003cusername\u003e \u003cpassword\u003e \"Role1,Role2...\"\n```\n\n### delete user\n\n```\nfastapi-auth-user-admin delete \u003cusername\u003e\n```\n\n### list users\n\n```\nfastapi-auth-user-admin list-users \n```\n\n### set password users\n\n```\nfastapi-auth-user-admin set-password \u003cusername\u003e \u003cnew-password\u003e \n```\n\n## Environment variables\n\n### AUTH_DEFAULT_KEY\n\n`AUTH_DEFAULT_KEY` is used as encryption key for the user's session information.\nIt is strongly recommended to set this value rather than depending on the\ndefault key as used in the code.\n\n### AUTH_DB_URI\n\n`AUTH_DB_URI` must be set to a SQL database. `zopyx-fastapi-auth` uses\n`sqlmodel` under the hood which uses `SQLAlchemy`and all supported databases\n(see https://docs.sqlalchemy.org/en/20/core/engines.html#database-urls). \n\nExample for using a SQLite database `users.db` inside the current working directory:\n\n```\nexport AUTH_DB_URI=sqlite:///users.db\n```\n\n### AUTH_LOG_FILENAME\n\nBy default, the module logs output to the console and to the `fastpi_auth.log`.\nYou can use a different filename by setting the `AUTH_LOG_FILENAME` environment\nvariable.\n\n## Internals\n\nThe implementation is based on top of the `starlette-session`\n(https://pypi.org/project/starlette-session/) middleware. The user information\nis stored through a  signed cookie-based HTTP session. Session information is\nreadable but not modifiable. The encryption key can be configured through an environment\nvariable.\n\n## Getting started with the included mini demo application\n\n### Installation\n\nCheckout the codebase and install it using pip or uv:\n\n```\npython3.12 -m venv .venv\nsource .venv/bin/activate\npip3 install -e .\n```\n\nor\n```\nuv venv -p python3.12\nsource .venv/bin/activate\nuv pip install -e .\n```\n\n### Create a demo user\n\n```\nfastapi-auth-user-admin add admin admin Administrator\n```\nThis will create a user `admin` with password `admin`.\n\n### Running the demo service\n\n```\nuvicorn fastapi_auth.demo_app:app\n```\n\n### Login into the demo application\n\nVisit http://localhost:8000/auth/login and login as `admin`/`admin`.\n\n![Login into application](/images/login.png)\n\n### After successfull login\n\n![Login into application](/images/logged-in.png)\n\n\n## Pluggable authenticators\n\nThis module provides a flexible architecture that allows the use of multiple\nauthentication and authorization backends within your FastAPI application. For\ninstance, you can configure the authentication system to use the default\nRelational Database Management System (RDBMS)-based user management,\nsupplemented with an additional plugin for Lightweight Directory Access Protocol\n(LDAP).\n\n### Example\n\nAn `Authenticator` is required to implement an `authenticate(request: Request)`\nmethod. This method should extract the login parameters from a login request and\nreturn a `Users` object. Authenticators need to be registered with the\n`AUTHENTICATOR_REGISTRY`. The execution order of the Authenticators is\ndetermined by their `position` parameter. A `position` of `0` indicates that the\nAuthenticator is the first to be used. A higher `position` value signifies a\nlower priority.\n\n```\nfrom fastapi import Request\nfrom fastapi.authenticator_registry import Authenticator, AUTHENTICATOR_REGISTRY\nfrom fastapi.users import User \n\nclass MyAuthenticator(Authenticator):\n\n    async def authenticate(request: Request) -\u003e User:\n\n        # extract credentials from request\n        username = request.form....\n        password = request.form....\n\n        # perform authentication against your own authentication system\n        user_data = my_backend.authenticate_user(username, password)\n        \n        return User(name=user_data[\"name\"], roles=[...])\n\nAUTHENTICATOR_REGISTRY.add_authenticator(MyAuthenticator(), 0)\n```\n\n## Provided routes\n\nThe `demo_app.py` application demonstrates the integration of `/auth/login` and\n`/auth/logout` routes. You can find the implementation of these routes in\n`auth_routes.py`. This code is customizable, allowing you to adapt it to your\nspecific requirements, as it includes some pre-configured decisions related to\nlogging and UI integration. The essence of the login process resides in the\n`login_post()` function. Given its simplicity and brevity, you should find it\nstraightforward to tailor the login procedure to your needs.\n\n## Author\n\nAndreas Jung \u003cinfo@zopyx.com\u003e\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fzopyx%2Ffastapi-auth","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fzopyx%2Ffastapi-auth","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fzopyx%2Ffastapi-auth/lists"}