{"id":14979098,"url":"https://github.com/tistaharahap/fastapi-jwt-auth3","last_synced_at":"2026-02-14T16:32:20.995Z","repository":{"id":243308711,"uuid":"812071416","full_name":"tistaharahap/fastapi-jwt-auth3","owner":"tistaharahap","description":"JWT authentication in FastAPI with ease","archived":false,"fork":false,"pushed_at":"2025-03-11T16:12:18.000Z","size":502,"stargazers_count":2,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-11-06T11:11:14.162Z","etag":null,"topics":["auth","fastapi","jwt","pydantic","python"],"latest_commit_sha":null,"homepage":"","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/tistaharahap.png","metadata":{"files":{"readme":"README.md","changelog":null,"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":"2024-06-07T22:32:05.000Z","updated_at":"2024-09-04T19:20:54.000Z","dependencies_parsed_at":null,"dependency_job_id":"4bf11083-a262-4e5f-aeff-f13e782b6c1d","html_url":"https://github.com/tistaharahap/fastapi-jwt-auth3","commit_stats":null,"previous_names":["tistaharahap/fastapi-jwt-auth"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/tistaharahap/fastapi-jwt-auth3","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tistaharahap%2Ffastapi-jwt-auth3","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tistaharahap%2Ffastapi-jwt-auth3/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tistaharahap%2Ffastapi-jwt-auth3/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tistaharahap%2Ffastapi-jwt-auth3/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/tistaharahap","download_url":"https://codeload.github.com/tistaharahap/fastapi-jwt-auth3/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tistaharahap%2Ffastapi-jwt-auth3/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":29449369,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-02-14T15:52:44.973Z","status":"ssl_error","status_checked_at":"2026-02-14T15:52:11.208Z","response_time":53,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.6:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"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":["auth","fastapi","jwt","pydantic","python"],"created_at":"2024-09-24T13:59:13.471Z","updated_at":"2026-02-14T16:32:20.978Z","avatar_url":"https://github.com/tistaharahap.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# FastAPI JWT Auth [![codecov](https://codecov.io/github/tistaharahap/fastapi-jwt-auth/graph/badge.svg?token=7UHRBSW1ZX)](https://codecov.io/github/tistaharahap/fastapi-jwt-auth)\n\nFastAPI JWT Auth is a lightweight library designed to simplify the integration of JWT authentication into FastAPI applications. By strictly adhering to FastAPI conventions, it provides a seamless and straightforward authentication setup process. The library aims for 100% test coverage.\n\n## Installing\n\n```bash\npip install fastapi-jwt-auth3\n```\n\n**NOTE:** There are others who have written similar libraries with identical names. As an homage to the libraries that came before, I have decided to name this library `fastapi-jwt-auth3`.\n\n## How To Use\n\nThis is an example single file implementation, let's name it `example.py`.\n\nIn order for this example to run, I took the liberty to use the `Faker` library to generate fake data. You can install it by running `pip install faker`.\n\n```python\n__all__ = [\"app\"]\n\nimport uuid\n\nfrom fastapi import FastAPI, Depends, HTTPException\n\nfrom faker import Faker\nfrom jwcrypto import jwk\nfrom pydantic import BaseModel, ConfigDict, EmailStr\nfrom fastapi_jwt_auth3.jwtauth import FastAPIJWTAuth, KeypairGenerator, JWTPresetClaims, generate_jwt_token\n\n# Initialize the Faker instance to generate fake data\nfake = Faker()\n\n\n# Define the token claims to be projected to when decoding JWT tokens\nclass TokenClaims(BaseModel):\n    model_config = ConfigDict(extra=\"forbid\")\n\n    name: str\n    email: EmailStr\n    iss: str\n    aud: str\n    exp: int\n    sub: str\n    iat: int\n    jti: str\n\n\n# Payload for our logins\nclass LoginIn(BaseModel):\n    username: str\n    password: str\n\n\napp = FastAPI(title=\"FastAPI JWT Auth Example\")\n\n# For the purpose of this example, we will generate a new RSA keypair\nprivate_key, public_key = KeypairGenerator.generate_rsa_keypair()\n\n# Create a JWK key from the public key\njwk_key = jwk.JWK.from_pem(public_key.encode(\"utf-8\"))\npublic_key_id = jwk_key.get(\"kid\")\n\n\"\"\"\n    Initialize the FastAPIJWTAuth instance with an RSA algorithm. We need to provide a set of private and public key.\n\"\"\"\njwt_auth = FastAPIJWTAuth(\n    algorithm=\"RS256\",\n    base_url=\"http://localhost:8000\",\n    secret_key=private_key,\n    public_key=public_key,\n    public_key_id=public_key_id,\n    issuer=\"https://localhost:8000\",\n    audience=\"https://localhost:8000\",\n    expiry=60 * 15,\n    refresh_token_expiry=60 * 60 * 24 * 7,\n    leeway=0,\n    project_to=TokenClaims,\n)\n\n\"\"\"\n    Initialize the FastAPIJWTAuth instance with a FastAPI app. This will add a route at:\n    \n    [GET] /.well-known/jwks.json\n    \n    This route will return the public key in JWK format for consumers to verify the JWT token.\n\"\"\"\njwt_auth.init_app(app)\n\n\n@app.get(\"/protected\")\nasync def protected_route(claims: TokenClaims = Depends(jwt_auth)):\n    return {\"message\": f\"Hello, {claims.name}!\"}\n\n\n@app.post(\"/login\")\nasync def login(payload: LoginIn):\n    if payload.username != \"username\" or payload.password != \"password\":\n        raise HTTPException(status_code=401, detail=\"Invalid credentials\")\n\n    preset_claims = JWTPresetClaims.factory(\n        issuer=jwt_auth.issuer, audience=jwt_auth.audience, expiry=jwt_auth.expiry, subject=str(uuid.uuid4())\n    )\n    claims = {\"name\": fake.name(), \"email\": fake.email()}\n    token = generate_jwt_token(\n        header=jwt_auth.header, secret_key=jwt_auth.secret_key, preset_claims=preset_claims, claims=claims\n    )\n    \n    # This is optional but good practice\n    refresh_token = jwt_auth.generate_refresh_token(access_token=token)\n    \n    return {\"access_token\": token, \"refresh_token\": refresh_token}\n```\n\nWe can run the example above with `uvicorn`. You can install with `pip install uvicorn`.\n\n```bash\nuvicorn example:app --reload\n```\n\n### Handling Refresh Tokens\n\nAs you can see in the examples above, you can optionally use a `refresh_token`. What this library does not cover is the handling of the `refresh_token`. You can implement your own logic to handle the refresh token. In terms of best practice, it's prudent to set a short expiry time for the `access_token` like 15 minutes and a longer expiry time for the `refresh_token` like 7 days.\n\nEvery `refresh_token` issued by the library will have the following claims attributed to it based on the access token. An example is below:\n\n```json\n{\n  \"iss\": \"https://localhost:8000\",\n  \"aud\": \"https://localhost:8000\",\n  \"exp\": 1719100800,\n  \"kid\": \"U790ZCw3aTvd3Z-Nzm5z2CdW7QFjlGk-HchE3EXhfR8\",\n  \"jku\": \"http://localhost:8000/.well-known/jwks.json\",\n  \"sub\": \"cbb6aa8b-a602-43fa-a578-76db183e3b2b\",\n  \"access_token_jti\": \"84db4b73-df2a-4690-802c-3c55247a6631\",\n  \"access_token_iat\": 1717933045\n}\n```\n\nRefresh token claims will always have the `access_token_jti` and `access_token_iat` claims. These claims are used to verify the integrity of the access token. If the access token is revoked, the refresh token will be invalidated when you set it up as such with your own logic.\n\n## Generating Keys\n\nThe library comes with a CLI tool called `keygen` to help you create keys for your application.\n\n![Keygen Help](images/keygen-help.gif)\n\nTo generate a new RSA keypair, you can run the following command:\n\n```bash\nkeygen --algorithm=RS256\n```\n\nThe private/public keys will be saved at the current working directory with the following filenames:\n\n```\nprivate_key.pem\npublic_key.pem\n```\n\nFor a list of the available algorithms supported, you can go here:\n\n[https://pyjwt.readthedocs.io/en/stable/algorithms.html](https://pyjwt.readthedocs.io/en/stable/algorithms.html)\n\n## Development\n\nThis project uses `rye` to build, test and publish the package. More about `rye` can be found in the link below:\n\n[https://rye.astral.sh/](https://rye.astral.sh/)\n\nPlease install `rye` first before continuing.\n\n### Environment Setup\n\nAfter `rye` is installed and available in your path, you can do the following to set up the environment:\n\n```bash\ngit clone git@github.com:tistaharahap/fastapi-jwt-auth.git\ncd fastapi-jwt-auth\nrye sync\n````\n\n### Testing\n\nTo run the tests, you can use the following command:\n\n```bash\nrye run test\n```\n\nWhen the command is run, coverage reports will be generated in these files and directory:\n\n```\nhtmlcov/\ncoverage.json\ncoverage.xml\n```\n\nCoverage report can be viewed as an HTML file by opening `htmlcov/index.html` in your browser.\n\nIn addition, coverage report is uploaded to `Codecov`, link [here](https://app.codecov.io/gh/tistaharahap/fastapi-jwt-auth). A Github action in the repository uploads the coverage report to `Codecov` automatically after successful tests.\n\nThis project aims to have 100% test coverage.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftistaharahap%2Ffastapi-jwt-auth3","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ftistaharahap%2Ffastapi-jwt-auth3","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftistaharahap%2Ffastapi-jwt-auth3/lists"}