{"id":28583077,"url":"https://github.com/maxrdu/fastapi_login","last_synced_at":"2025-06-11T05:04:07.711Z","repository":{"id":38147819,"uuid":"216593146","full_name":"maxrdu/fastapi_login","owner":"maxrdu","description":"FastAPI-Login tries to provide similar functionality as Flask-Login does.","archived":false,"fork":false,"pushed_at":"2025-05-20T07:04:51.000Z","size":921,"stargazers_count":674,"open_issues_count":1,"forks_count":63,"subscribers_count":10,"default_branch":"master","last_synced_at":"2025-06-08T20:01:54.858Z","etag":null,"topics":["fastapi","plugin","python3"],"latest_commit_sha":null,"homepage":"https://pypi.org/project/fastapi-login","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/maxrdu.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,"zenodo":null}},"created_at":"2019-10-21T14:47:00.000Z","updated_at":"2025-05-20T07:04:56.000Z","dependencies_parsed_at":"2024-01-03T02:29:53.580Z","dependency_job_id":"c90e4806-b2e0-4fd0-ac79-fc8ee0704ffb","html_url":"https://github.com/maxrdu/fastapi_login","commit_stats":{"total_commits":415,"total_committers":16,"mean_commits":25.9375,"dds":0.1253012048192771,"last_synced_commit":"00adde8f358c5a72f33e2938de0966d1c092db5b"},"previous_names":[],"tags_count":25,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/maxrdu%2Ffastapi_login","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/maxrdu%2Ffastapi_login/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/maxrdu%2Ffastapi_login/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/maxrdu%2Ffastapi_login/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/maxrdu","download_url":"https://codeload.github.com/maxrdu/fastapi_login/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/maxrdu%2Ffastapi_login/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":259204802,"owners_count":22821159,"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":["fastapi","plugin","python3"],"created_at":"2025-06-11T05:01:46.314Z","updated_at":"2025-06-11T05:04:07.698Z","avatar_url":"https://github.com/maxrdu.png","language":"Python","readme":"# FastAPI-Login\n\n[![CI](https://img.shields.io/github/actions/workflow/status/MushroomMaula/fastapi_login/ci.yml)](https://github.com/MushroomMaula/fastapi_login/actions)\n[![PyPI - Python Version](https://img.shields.io/pypi/pyversions/fastapi-login.svg)](https://pypi.org/project/fastapi-login/)\n[![PyPI](https://img.shields.io/pypi/v/fastapi-login.svg)](https://pypi.org/project/fastapi-login/)\n[![License](https://img.shields.io/github/license/MushroomMaula/fastapi_login.svg)](https://github.com/MushroomMaula/fastapi_login)\n\nFastAPI-Login tries to provide similar functionality as [Flask-Login](https://github.com/maxcountryman/flask-login) does.\n\n## Documentation\n\nIn-depth documentation can be found at [fastapi-login.readthedocs.io](https://fastapi-login.readthedocs.io/).\n\nSome examples can be found [here](https://github.com/MushroomMaula/fastapi_login/tree/master/examples).\n\n## Installation\n\n```shell script\npip install fastapi-login\n```\n\n## Usage\n\nTo begin we have to set up our FastAPI app:\n\n```python\nfrom fastapi import FastAPI\n\nSECRET = 'your-secret-key'\n\napp = FastAPI()\n```\n\nTo obtain a suitable secret key you can run `import secrets; print(secrets.token_hex(24))`.\n\nNow we can import and setup the `LoginManager`, which will handle the process of encoding and decoding our Json Web Tokens.\n\n```python\nfrom fastapi_login import LoginManager\n\nmanager = LoginManager(SECRET, token_url='/auth/token')\n```\n\nFor the example we will use a dictionary to represent our user database. In your\napplication this could also be a real database like sqlite or Postgres. It does not\nmatter as you have to provide the function which retrieves the user.\n\n```python\nfake_db = {'johndoe@e.mail': {'password': 'hunter2'}}\n```\n\nNow we have to provide the ``LoginManager`` with a way to load our user. The\n`user_loader` callback should either return your user object or ``None``\n\n```python\n@manager.user_loader()\ndef load_user(email: str):  # could also be an asynchronous function\n    user = fake_db.get(email)\n    return user\n```\n\nNow we have to define a way to let the user login in our app. Therefore we will create\na new route:\n\n```python\nfrom fastapi import Depends\nfrom fastapi.security import OAuth2PasswordRequestForm\nfrom fastapi_login.exceptions import InvalidCredentialsException\n\n# the python-multipart package is required to use the OAuth2PasswordRequestForm\n@app.post('/auth/token')\ndef login(data: OAuth2PasswordRequestForm = Depends()):\n    email = data.username\n    password = data.password\n\n    user = load_user(email)  # we are using the same function to retrieve the user\n    if not user:\n        raise InvalidCredentialsException  # you can also use your own HTTPException\n    elif password != user['password']:\n        raise InvalidCredentialsException\n\n    access_token = manager.create_access_token(\n        data=dict(sub=email)\n    )\n    return {'access_token': access_token, 'token_type': 'bearer'}\n```\n\nNow whenever you want your user to be logged in to use a route, you can simply\nuse your ``LoginManager`` instance as a dependency.\n\n```python\n@app.get('/protected')\ndef protected_route(user=Depends(manager)):\n    ...\n```\n\nIf you also want to handle a not authenticated error, you can add your own subclass of Exception to the LoginManager.\n\n```python\nfrom starlette.responses import RedirectResponse\n\nclass NotAuthenticatedException(Exception):\n    pass\n\n# these two argument are mandatory\ndef exc_handler(request, exc):\n    return RedirectResponse(url='/login')\n\n\nmanager = LoginManager(..., not_authenticated_exception=NotAuthenticatedException)\n# You also have to add an exception handler to your app instance\napp.add_exception_handler(NotAuthenticatedException, exc_handler)\n```\n\nTo change the expiration date of the token use the ``expires_delta`` argument of the `create_access_token` method\nwith `timedelta`. The default is set 15 min. Please be aware that setting a long expiry date is not considered a good practice\nas it would allow an attacker with the token to use your application as long as he wants.\n\n```python\nfrom datetime import timedelta\n\ndata = dict(sub=user.email)\n\n# expires after 15 min\ntoken = manager.create_access_token(\n    data=data\n)\n# expires after 12 hours\nlong_token = manager.create_access_token(\n    data=data, expires=timedelta(hours=12)\n)\n```\n\n### Usage with cookies\n\nInstead of checking the header for the token. ``fastapi-login``  also support access using cookies.\n\n```python\nfrom fastapi_login import LoginManager\n\nmanager = LoginManager(SECRET, token_url='/auth/token', use_cookie=True)\n```\n\nNow the manager will check the requests cookies the headers for the access token. The name of the cookie can be set using\n ``manager.cookie_name``.\nIf you only want to check the requests cookies you can turn the headers off using the ``use_header`` argument\n\nFor convenience the LoginManager also includes the ``set_cookie`` method which sets the cookie to your response,\nwith the recommended HTTPOnly flag and the ``manager.cookie_name`` as the key.\n\n```python\nfrom fastapi import Depends\nfrom starlette.responses import Response\n\n\n@app.get('/auth')\ndef auth(response: Response, user=Depends(manager)):\n    token = manager.create_access_token(\n        data=dict(sub=user.email)\n    )\n    manager.set_cookie(response, token)\n    return response\n```\n","funding_links":[],"categories":["Python","Authorization \u0026 Authentication","Third-Party Extensions"],"sub_categories":["Auth"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmaxrdu%2Ffastapi_login","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmaxrdu%2Ffastapi_login","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmaxrdu%2Ffastapi_login/lists"}