{"id":19645779,"url":"https://github.com/approov/quickstart-python-fastapi-token-check","last_synced_at":"2025-02-26T23:45:16.743Z","repository":{"id":96186293,"uuid":"344932036","full_name":"approov/quickstart-python-fastapi-token-check","owner":"approov","description":"Quickstart Approov integration example for the Python FastAPI framework","archived":false,"fork":false,"pushed_at":"2024-10-15T19:08:30.000Z","size":51,"stargazers_count":1,"open_issues_count":1,"forks_count":0,"subscribers_count":7,"default_branch":"main","last_synced_at":"2025-01-09T20:53:34.903Z","etag":null,"topics":["api","api-security","approov","approov-api","approov-backend-quicksart","approov-integration","approov-quickstart","approov-token","backend","security"],"latest_commit_sha":null,"homepage":"https://approov.io","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/approov.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":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2021-03-05T20:56:27.000Z","updated_at":"2024-05-17T13:25:46.000Z","dependencies_parsed_at":"2024-04-25T07:24:12.244Z","dependency_job_id":"c01dc134-50ee-4ed5-9447-a136ce2fddf0","html_url":"https://github.com/approov/quickstart-python-fastapi-token-check","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/approov%2Fquickstart-python-fastapi-token-check","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/approov%2Fquickstart-python-fastapi-token-check/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/approov%2Fquickstart-python-fastapi-token-check/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/approov%2Fquickstart-python-fastapi-token-check/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/approov","download_url":"https://codeload.github.com/approov/quickstart-python-fastapi-token-check/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":240952991,"owners_count":19884020,"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":["api","api-security","approov","approov-api","approov-backend-quicksart","approov-integration","approov-quickstart","approov-token","backend","security"],"created_at":"2024-11-11T14:35:12.237Z","updated_at":"2025-02-26T23:45:16.726Z","avatar_url":"https://github.com/approov.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Approov QuickStart - Python FastAPI Token Check\n\n[Approov](https://approov.io) is an API security solution used to verify that requests received by your backend services originate from trusted versions of your mobile apps.\n\nThis repo implements the Approov server-side request verification code with the Python FastAPI framework, which performs the verification check before allowing valid traffic to be processed by the API endpoint.\n\n\n## Approov Integration Quickstart\n\nThe quickstart was tested with the following Operating Systems:\n\n* Ubuntu 20.04\n* MacOS Big Sur\n* Windows 10 WSL2 - Ubuntu 20.04\n\nFirst, setup the [Approov CLI](https://approov.io/docs/latest/approov-installation/index.html#initializing-the-approov-cli).\n\nNow, register the API domain for which Approov will issues tokens:\n\n```bash\napproov api -add api.example.com\n```\n\n\u003e **NOTE:** By default a symmetric key (HS256) is used to sign the Approov token on a valid attestation of the mobile app for each API domain it's added with the Approov CLI, so that all APIs will share the same secret and the backend needs to take care to keep this secret secure.\n\u003e\n\u003e A more secure alternative is to use asymmetric keys (RS256 or others) that allows for a different keyset to be used on each API domain and for the Approov token to be verified with a public key that can only verify, but not sign, Approov tokens.\n\u003e\n\u003e To implement the asymmetric key you need to change from using the symmetric HS256 algorithm to an asymmetric algorithm, for example RS256, that requires you to first [add a new key](https://approov.io/docs/latest/approov-usage-documentation/#adding-a-new-key), and then specify it when [adding each API domain](https://approov.io/docs/latest/approov-usage-documentation/#keyset-key-api-addition). Please visit [Managing Key Sets](https://approov.io/docs/latest/approov-usage-documentation/#managing-key-sets) on the Approov documentation for more details.\n\nNext, enable your Approov `admin` role with:\n\n```bash\neval `approov role admin`\n````\n\nFor the Windows powershell:\n\n```bash\nset APPROOV_ROLE=admin:___YOUR_APPROOV_ACCOUNT_NAME_HERE___\n```\n\nNow, get your Approov Secret with the [Approov CLI](https://approov.io/docs/latest/approov-installation/index.html#initializing-the-approov-cli):\n\n```bash\napproov secret -get base64\n```\n\nNext, add the [Approov secret](https://approov.io/docs/latest/approov-usage-documentation/#account-secret-key-export) to your project `.env` file:\n\n```env\nAPPROOV_BASE64_SECRET=approov_base64_secret_here\n```\n\nNow, add to your `requirements.txt` file the [JWT dependency](https://github.com/jpadilla/pyjwt/):\n\n```bash\nPyJWT==1.7.1 # update the version to the latest one\n```\n\nNext, you need to install the dependencies:\n\n```bash\npip3 install -r requirements.txt\n```\n\nNow, add this code to your project, just before your first API endpoint:\n\n```python\nfrom fastapi import FastAPI, Request\nfrom fastapi.responses import JSONResponse\n\n# @link https://github.com/jpadilla/pyjwt/\nimport jwt\nimport base64\n\n# @link https://github.com/theskumar/python-dotenv\nfrom dotenv import load_dotenv, find_dotenv\nload_dotenv(find_dotenv(), override=True)\nfrom os import getenv\n\n# Token secret value obtained with the Approov CLI tool:\n#  - approov secret -get\napproov_base64_secret = getenv('APPROOV_BASE64_SECRET')\n\nif approov_base64_secret == None:\n    raise ValueError(\"Missing the value for environment variable: APPROOV_BASE64_SECRET\")\n\nAPPROOV_SECRET = base64.b64decode(approov_base64_secret)\n\napp = FastAPI()\n\n################################################################################\n# ONLY ADD YOUR MIDDLEWARE BEFORE THIS LINE.\n# - FastAPI seems to execute middleware in the reverse we declare it in the\n#   code.\n# - Approov middleware SHOULD be the first to be executed in the request life\n#   cycle.\n################################################################################\n\n# @link https://approov.io/docs/latest/approov-usage-documentation/#backend-integration\n# @IMPORTANT FastAPI seems to execute middleware in the reverse order they\n#            appear in the code, therefore this one must come as the LAST of the\n#            middleware's.\n@app.middleware(\"http\")\nasync def verifyApproovToken(request: Request, call_next):\n    approov_token = request.headers.get(\"Approov-Token\")\n\n    # If we didn't find a token, then reject the request.\n    if approov_token == \"\":\n        # You may want to add some logging here.\n        # return None\n        return JSONResponse({}, status_code = 401)\n\n    try:\n        # Decode the Approov token explicitly with the HS256 algorithm to avoid\n        # the algorithm None attack.\n        approov_token_claims = jwt.decode(approov_token, APPROOV_SECRET, algorithms=['HS256'])\n        return await call_next(request)\n    except jwt.ExpiredSignatureError as e:\n        # You may want to add some logging here.\n        return JSONResponse({}, status_code = 401)\n    except jwt.InvalidTokenError as e:\n        # You may want to add some logging here.\n        return JSONResponse({}, status_code = 401)\n\n# @app.get(\"/\")\n# async def root():\n#     return {\"message\": \"Hello World\"}\n```\n\n\u003e **NOTE:** When the Approov token validation fails we return a `401` with an empty body, because we don't want to give clues to an attacker about the reason the request failed, and you can go even further by returning a `400`.\n\nUsing the middleware approach will ensure that all endpoints in your API will be protected by Approov.\n\nNot enough details in the bare bones quickstart? No worries, check the [detailed quickstarts](QUICKSTARTS.md) that contain a more comprehensive set of instructions, including how to test the Approov integration.\n\n\n## More Information\n\n* [Approov Overview](OVERVIEW.md)\n* [Detailed Quickstarts](QUICKSTARTS.md)\n* [Examples](EXAMPLES.md)\n* [Testing](TESTING.md)\n\n### System Clock\n\nIn order to correctly check for the expiration times of the Approov tokens is very important that the backend server is synchronizing automatically the system clock over the network with an authoritative time source. In Linux this is usually done with a NTP server.\n\n\n## Issues\n\nIf you find any issue while following our instructions then just report it [here](https://github.com/approov/quickstart-python-fastapi-token-check/issues), with the steps to reproduce it, and we will sort it out and/or guide you to the correct path.\n\n\n## Useful Links\n\nIf you wish to explore the Approov solution in more depth, then why not try one of the following links as a jumping off point:\n\n* [Approov Free Trial](https://approov.io/signup)(no credit card needed)\n* [Approov Get Started](https://approov.io/product/demo)\n* [Approov QuickStarts](https://approov.io/docs/latest/approov-integration-examples/)\n* [Approov Docs](https://approov.io/docs)\n* [Approov Blog](https://approov.io/blog/)\n* [Approov Resources](https://approov.io/resource/)\n* [Approov Customer Stories](https://approov.io/customer)\n* [Approov Support](https://approov.io/contact)\n* [About Us](https://approov.io/company)\n* [Contact Us](https://approov.io/contact)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fapproov%2Fquickstart-python-fastapi-token-check","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fapproov%2Fquickstart-python-fastapi-token-check","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fapproov%2Fquickstart-python-fastapi-token-check/lists"}