{"id":25799391,"url":"https://github.com/sahaspunchihewa/fastapi-keycloak-auth","last_synced_at":"2026-02-04T00:40:40.075Z","repository":{"id":268334263,"uuid":"904030215","full_name":"SahasPunchihewa/fastapi-keycloak-auth","owner":"SahasPunchihewa","description":"Keycloak authentication for FastAPI that helps to secure your API endpoints with RBAC with minimal configurations","archived":false,"fork":false,"pushed_at":"2024-12-17T16:24:09.000Z","size":9,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-02-20T18:17:51.719Z","etag":null,"topics":["fastapi","keycloak","keycloak-client","python","python-keycloak","python3","rbac"],"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/SahasPunchihewa.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}},"created_at":"2024-12-16T05:49:41.000Z","updated_at":"2024-12-16T11:07:49.000Z","dependencies_parsed_at":"2024-12-16T06:17:27.209Z","dependency_job_id":"f3b3f4bd-a36c-4ff8-8628-ee4407488628","html_url":"https://github.com/SahasPunchihewa/fastapi-keycloak-auth","commit_stats":null,"previous_names":["sahaspunchihewa/fastapi-keycloak-auth"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/SahasPunchihewa%2Ffastapi-keycloak-auth","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/SahasPunchihewa%2Ffastapi-keycloak-auth/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/SahasPunchihewa%2Ffastapi-keycloak-auth/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/SahasPunchihewa%2Ffastapi-keycloak-auth/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/SahasPunchihewa","download_url":"https://codeload.github.com/SahasPunchihewa/fastapi-keycloak-auth/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":241030503,"owners_count":19897110,"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","keycloak","keycloak-client","python","python-keycloak","python3","rbac"],"created_at":"2025-02-27T15:46:55.348Z","updated_at":"2026-02-04T00:40:35.025Z","avatar_url":"https://github.com/SahasPunchihewa.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# **FastAPI Keycloak Auth** ![Version](https://img.shields.io/badge/version-1.0.0-blue) ![License](https://img.shields.io/badge/license-MIT-green)\n\u003cbr\u003e\n\u003cimg src=\"https://img.shields.io/badge/FastAPI-009688?style=for-the-badge\u0026logo=fastapi\u0026logoColor=white\"  alt=\"Fast API\"/\u003e\n\u003cimg src=\"https://img.shields.io/badge/Keycloak-103060?style=for-the-badge\u0026logo=keycloak\u0026logoColor=white\"  alt=\"Keycloak\"/\u003e\n\n\nA lightweight library to secure FastAPI APIs using Keycloak, enabling **Role-Based Access Control (RBAC)** with minimal configuration.\n\n---\n\n## **Features**\n\n- Simple integration with Keycloak for FastAPI applications.\n- Built-in support for Role-Based Access Control (RBAC) using Keycloak roles.\n- Works seamlessly with both realm roles and client roles.\n- Automatically decodes and validates JWT tokens.\n\n---\n\n## **Minimum Requirements**\n\n- **Python**: 3.12 or higher\n- **FastAPI**: 0.115.6 or higher\n- **Keycloak**: 5.1.1 or higher\n\n---\n\n## **Installation**\n\nInstall the library using pip:\n\n```bash\npip install fastapi-keycloak-auth\n```\n\n---\n\n## **Usage Guide**\n\n### **1. Initialize KeycloakAuth**\n\nStart by initializing the `KeycloakAuth` instance with your Keycloak server configuration.\nThere are two ways that you can use to initialize the `KeycloakAuth` instance:\n\n1. Providing keycloak configurations as arguments in the initializer\n\n      ```python\n      from keycloak_auth.keycloak_auth import KeycloakAuth\n      \n      auth = KeycloakAuth(\n      server_url=KEYCLOAK_URL,\n      client_id=KEYCLOAK_CLIENT_ID,\n      realm_name=KEYCLOAK_REALM_NAME,\n      client_secret_key=KEYCLOAK_CLIENT_SECRET,\n      use_resource_access=True\n      )\n      ```\n   Replace `KEYCLOAK_URL`, `KEYCLOAK_CLIENT_ID`, `KEYCLOAK_REALM_NAME`, and `KEYCLOAK_CLIENT_SECRET` with your Keycloak instance details.\n\n    * `server_url`: The URL of your Keycloak server. Ex: `http://localhost:8080/auth/`\n    * `client_id`: The client ID of your Keycloak client.\n    * `realm_name`: The name of your Keycloak realm.\n    * `client_secret_key`: The client secret of your Keycloak client.\n    * `use_resource_access`: Set to `True` if you want to use client roles in RBAC instead of realm roles (Default is set to `False`).\n\n\n2. Setting up Keycloak configurations as environmental variables (This method is recommended when this application is running in a containerized environment)\n\n    ```python\n    from keycloak_auth.keycloak_auth import KeycloakAuth\n    import os\n    \n    os.environ['KEYCLOAK_URL'] = KEYCLOAK_URL\n    os.environ['KEYCLOAK_CLIENT_ID'] = KEYCLOAK_CLIENT_ID\n    os.environ['KEYCLOAK_REALM_NAME'] = KEYCLOAK_REALM_NAME\n    os.environ['KEYCLOAK_CLIENT_SECRET'] = KEYCLOAK_CLIENT_SECRET\n    \n    auth = KeycloakAuth()\n    ```\n   Replace `KEYCLOAK_URL`, `KEYCLOAK_CLIENT_ID`, `KEYCLOAK_REALM_NAME`, and `KEYCLOAK_CLIENT_SECRET` with your Keycloak instance details.\n\n    * `KEYCLOAK_URL`: The URL of your Keycloak server. Ex: `http://localhost:8080/auth/`\n    * `KEYCLOAK_CLIENT_ID`: The client ID of your Keycloak client.\n    * `KEYCLOAK_REALM_NAME`: The name of your Keycloak realm.\n    * `KEYCLOAK_CLIENT_SECRET`: The client secret of your Keycloak client.\n\n---\n\n### **2. Protect Routes with Roles**\n\nUse the `RolesAllowed` decorator to protect your FastAPI routes based on roles defined in Keycloak.\nYou can pass a list of roles that are allowed to access the route.\n\n***Important Note:*** make sure to add `authorization: str | None = Header(default=None)` as a parameter in the route function to receive the JWT token.\nOtherwise, the library will not be able to decode and validate the token.\n\n```python\nfrom fastapi import FastAPI, Header\nfrom keycloak_auth.keycloak_auth import KeycloakAuth\n\napp = FastAPI()\n\nauth: KeycloakAuth = KeycloakAuth(\n    server_url=KEYCLOAK_URL,\n    client_id=KEYCLOAK_CLIENT_ID,\n    realm_name=KEYCLOAK_REALM_NAME,\n    client_secret_key=KEYCLOAK_CLIENT_SECRET,\n    use_resource_access=True\n)\n\n\n@app.get('/admin')\n@auth.RolesAllowed(['admin'])\nasync def admin_route(authorization: str | None = Header(default=None)):\n    return {'message': 'Hello Admin'}\n\n\n@app.get('/user')\n@auth.RolesAllowed(['admin', 'user'])\nasync def user_route(authorization: str | None = Header(default=None)):\n    return {'message': 'Hello User'}\n```\n\n[See Full Code Example](https://github.com/SahasPunchihewa/fastapi-keycloak-rbac-poc)\n\n---\n\n### **3. Additional Features**\n\n1. You can also use the `KeycloakAuth` instance to decode and validate JWT tokens manually.\n\n    ```python\n    from keycloak_auth.keycloak_auth import KeycloakAuth\n\n    auth = KeycloakAuth()\n   \n    token = auth.current_token\n    ```\n\n2. You can use the `KeycloakAuth` instance to get the current user's profile.\n\n    ```python\n    from keycloak_auth.keycloak_auth import KeycloakAuth\n\n    auth = KeycloakAuth()\n   \n    user = auth.get_user_info()\n    ```\n\n---\n\n### **4. Custom Error Handling**\n\nThe library automatically raises HTTPException for errors such as:\n\n* `401 Unauthorized`: When the token is missing or expired.\n* `403 Forbidden`: When the user does not have sufficient permissions.\n* For advanced scenarios, you can implement additional error handling logic in your application.\n\n## **License**\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsahaspunchihewa%2Ffastapi-keycloak-auth","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsahaspunchihewa%2Ffastapi-keycloak-auth","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsahaspunchihewa%2Ffastapi-keycloak-auth/lists"}