{"id":23703199,"url":"https://github.com/imjoseangel/fastapi-keycloak","last_synced_at":"2026-04-29T22:07:35.307Z","repository":{"id":269274583,"uuid":"906919798","full_name":"imjoseangel/fastapi-keycloak","owner":"imjoseangel","description":"This project demonstrates how to integrate Keycloak with a FastAPI application using Docker and Docker Compose for authentication.","archived":false,"fork":false,"pushed_at":"2024-12-28T18:33:17.000Z","size":6117,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"devel","last_synced_at":"2024-12-30T13:00:43.491Z","etag":null,"topics":["authentication","fastapi","keycloak","python","security"],"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/imjoseangel.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":"2024-12-22T10:02:55.000Z","updated_at":"2024-12-28T18:33:20.000Z","dependencies_parsed_at":"2024-12-22T11:28:20.145Z","dependency_job_id":"bbabcae9-538a-4a8e-863f-736102d64ce4","html_url":"https://github.com/imjoseangel/fastapi-keycloak","commit_stats":null,"previous_names":["imjoseangel/fastapi-keycloak"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/imjoseangel%2Ffastapi-keycloak","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/imjoseangel%2Ffastapi-keycloak/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/imjoseangel%2Ffastapi-keycloak/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/imjoseangel%2Ffastapi-keycloak/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/imjoseangel","download_url":"https://codeload.github.com/imjoseangel/fastapi-keycloak/tar.gz/refs/heads/devel","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":239780144,"owners_count":19695735,"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":["authentication","fastapi","keycloak","python","security"],"created_at":"2024-12-30T13:00:47.886Z","updated_at":"2026-01-31T04:30:16.101Z","avatar_url":"https://github.com/imjoseangel.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# FastAPI Keycloak Integration\n\n![Integrating FastAPI with Keycloak for Authentication](./assets/Integrating%20FastAPI%20with%20Keycloak%20for%20Authentication.png)\n\nThis project demonstrates how to integrate [Keycloak](https://www.keycloak.org/) with a [FastAPI](https://fastapi.tiangolo.com/) application using Docker and Docker Compose for authentication.\n\n## Table of Contents\n\n- [Introduction](#introduction)\n- [Features](#features)\n- [Prerequisites](#prerequisites)\n- [Installation](#installation)\n- [Configuration](#configuration)\n- [Usage](#usage)\n- [Authentication Flow](#authentication-flow)\n- [Testing the Authentication](#testing-the-authentication)\n- [Contributing](#contributing)\n- [License](#license)\n\n## Introduction\n\nThis project provides a template for securing a FastAPI application using Keycloak as the identity provider. It uses Docker and Docker Compose for containerization and easy deployment. Dependency management is handled using Poetry.\n\n## Features\n\n- **FastAPI Application**: A modern, fast web framework for building APIs with Python 3.12+.\n- **Keycloak Integration**: Secure your API endpoints with Keycloak's robust authentication and authorization features.\n- **Custom Login Endpoint**: Authenticate users via a `/login` endpoint that returns an access token.\n- **Dockerized Setup**: Use Docker and Docker Compose for seamless development and deployment.\n- **Poetry for Dependency Management**: Simplify your Python dependencies and virtual environments.\n\n## Prerequisites\n\n- [Python 3.12](https://www.python.org/downloads/)\n- [Docker](https://www.docker.com/get-started)\n- [Docker Compose](https://docs.docker.com/compose/install/)\n- [Git](https://git-scm.com/)\n- **Up and Running Keycloak Server**\n\n  Ensure that you have a Keycloak server up and running, configured with the appropriate realm, client, and user. This can be set up separately or included in your Docker Compose configuration.\n\n## Installation\n\n1. **Clone the Repository**\n\n   ```bash\n   git clone https://github.com/anqorithm/fastapi-keycloak.git\n   cd fastapi-keycloak\n   ```\n\n2. **Copy Environment Variables File**\n\n   Navigate to the `src` directory and copy the `.env.example` file to `.env`:\n\n   ```bash\n   cd src\n   mv .env.example .env\n   ```\n\n3. **Configure Environment Variables**\n\n   Open the `.env` file and update the following variables with your Keycloak configuration:\n\n   - `KEYCLOAK_SERVER_URL`: The URL where your Keycloak server is running (e.g., `http://keycloak:8080/`).\n   - `KEYCLOAK_REALM`: Your Keycloak realm name (e.g., `fastapi-realm`).\n   - `KEYCLOAK_CLIENT_ID`: The client ID you set up in Keycloak (e.g., `fastapi-client`).\n   - `KEYCLOAK_CLIENT_SECRET`: The client secret obtained from Keycloak.\n\n4. **Set Up Keycloak**\n\n   Ensure that Keycloak is configured with the appropriate realm, client, and user. Refer to the [Configuration](#configuration) section for detailed steps.\n\n## Configuration\n\n### Setting Up Keycloak Server\n\n1. **Start Keycloak**\n\n   - Ensure your Keycloak server is up and running.\n   - You can run Keycloak separately or include it in your `docker-compose.yml`.\n\n2. **Access the Keycloak Admin Console**\n\n   - Open your browser and navigate to `http://localhost:8080/` (or the appropriate URL).\n   - Log in with your admin credentials.\n\n3. **Create a New Realm**\n\n   - Click on **Add Realm** in the admin console.\n   - Provide a name for your realm (e.g., `fastapi-realm`).\n   - Click **Create**.\n\n4. **Create a New Client**\n\n   - Navigate to the **Clients** section within your realm.\n   - Click **Create**.\n   - Enter your client ID (e.g., `fastapi-client`).\n   - Set the Client Protocol to `openid-connect`.\n   - Click **Save**.\n   - In the client settings:\n     - Set **Access Type** to `confidential`.\n     - Enable **Standard Flow Enabled** and **Direct Access Grants Enabled**.\n     - In **Valid Redirect URIs**, add `http://localhost:8000/*`.\n     - Click **Save**.\n\n5. **Obtain Client Secret**\n\n   - Go to the **Credentials** tab of your client.\n   - Copy the **Secret** value.\n   - Update your `.env` file with this secret.\n\n6. **Create a Test User**\n\n   - Navigate to the **Users** section.\n   - Click **Add User**.\n   - Fill out the required fields (e.g., username: `testuser`).\n   - Click **Save**.\n   - Go to the **Credentials** tab.\n   - Set a password and disable the **Temporary** option.\n   - Click **Set Password**.\n\n## Usage\n\n### Running the Application\n\n- Start the application using Docker Compose:\n\n  ```bash\n  docker-compose up --build\n  ```\n\n- This command builds the Docker image and starts the containers specified in the `docker-compose.yml` file.\n\n### Accessing the Services\n\n- **FastAPI Application**: `http://localhost:8000/`\n- **Keycloak Admin Console**: `http://localhost:8080/`\n\n## Authentication Flow\n\n### Login Endpoint\n\nThe application includes a `/login` endpoint that allows users to authenticate by providing their username and password. Upon successful authentication, an access token is returned, which can be used to access protected routes.\n\n- **Endpoint**: `/login`\n- **Method**: `POST`\n- **Parameters**:\n  - `username`: The user's username.\n  - `password`: The user's password.\n- **Response**:\n  - Returns a JSON object containing the access token.\n\n**Note**: The `/login` endpoint accepts form data (`application/x-www-form-urlencoded`).\n\n### Protected Endpoint\n\n- **Endpoint**: `/protected`\n- **Method**: `GET`\n- **Headers**:\n  - `Authorization`: `Bearer \u003caccess_token\u003e`\n- **Response**:\n  - Returns a greeting message containing the username.\n\n## Testing the Authentication\n\n1. **Access Protected Endpoint Without Token**\n\n   - Navigate to `http://localhost:8000/protected`.\n   - You should receive a `401 Unauthorized` response.\n\n2. **Obtain an Access Token via Login Endpoint**\n\n   - Use a tool like `curl` or Postman to make a POST request to the `/login` endpoint.\n\n     - **Example using `curl`**:\n\n       ```bash\n       curl -X POST http://localhost:8000/login \\\n         -H \"Content-Type: application/x-www-form-urlencoded\" \\\n         -d \"username=testuser\u0026password=yourpassword\"\n       ```\n\n       Replace `testuser` and `yourpassword` with the credentials of the user you created in Keycloak.\n\n   - **Response**:\n\n     The response will be a JSON object containing the `access_token`. For example:\n\n     ```json\n     {\n       \"access_token\": \"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...\"\n     }\n     ```\n\n3. **Access Protected Endpoint With Token**\n\n   - Use the obtained `access_token` to access the protected endpoint.\n\n     - **Example using `curl`**:\n\n       ```bash\n       curl -X GET http://localhost:8000/protected \\\n         -H \"Authorization: Bearer your_access_token\"\n       ```\n\n       Replace `your_access_token` with the token received from the `/login` endpoint.\n\n   - **Expected Response**:\n\n     ```json\n     {\n       \"message\": \"Hello, testuser\"\n     }\n     ```\n\n## Contributing\n\nContributions are welcome! Please feel free to submit a pull request or open an issue.\n\n## License\n\nThis project is licensed under the MIT License.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fimjoseangel%2Ffastapi-keycloak","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fimjoseangel%2Ffastapi-keycloak","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fimjoseangel%2Ffastapi-keycloak/lists"}