{"id":27103025,"url":"https://github.com/yoanesber/spring-boot-jwt-auth-kong","last_synced_at":"2026-05-13T23:35:32.773Z","repository":{"id":285205774,"uuid":"954856216","full_name":"yoanesber/Spring-Boot-JWT-Auth-Kong","owner":"yoanesber","description":"This project is a Spring Boot REST API for managing department data, integrated with Kong API Gateway running in DB-Backed Mode with PostgreSQL. The Kong JWT Plugin is enabled for authentication, allowing secure access to the API without modifying the application code.","archived":false,"fork":false,"pushed_at":"2025-03-30T08:46:51.000Z","size":16,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-03-30T09:27:07.514Z","etag":null,"topics":["api-gateway","jwt-auth","kong","rest-api","spring-boot"],"latest_commit_sha":null,"homepage":"","language":"Java","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/yoanesber.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":"2025-03-25T18:10:20.000Z","updated_at":"2025-03-30T08:46:55.000Z","dependencies_parsed_at":"2025-03-30T09:27:11.370Z","dependency_job_id":"48ed8b2d-2b55-4627-9887-7c02c2d67c49","html_url":"https://github.com/yoanesber/Spring-Boot-JWT-Auth-Kong","commit_stats":null,"previous_names":["yoanesber/spring-boot-jwt-auth-kong"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yoanesber%2FSpring-Boot-JWT-Auth-Kong","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yoanesber%2FSpring-Boot-JWT-Auth-Kong/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yoanesber%2FSpring-Boot-JWT-Auth-Kong/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yoanesber%2FSpring-Boot-JWT-Auth-Kong/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/yoanesber","download_url":"https://codeload.github.com/yoanesber/Spring-Boot-JWT-Auth-Kong/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247516568,"owners_count":20951705,"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-gateway","jwt-auth","kong","rest-api","spring-boot"],"created_at":"2025-04-06T16:38:32.907Z","updated_at":"2025-10-15T06:43:50.931Z","avatar_url":"https://github.com/yoanesber.png","language":"Java","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Spring Boot Department API with Kong JWT Authentication (DB-Backed Mode)\n\n## 📖 Overview\nThis project is a **Spring Boot REST API** for managing department data. It integrates **Kong API Gateway** as a reverse proxy and security layer, running in **DB-Backed Mode with PostgreSQL**. The **JWT Plugin** is enabled to handle authentication **without modifying the application code**.  \n\nThis project is built and developed on **Windows**, using **WSL (Windows Subsystem for Linux) to run Kong**, while **PostgreSQL is installed on Windows**. Since Kong runs inside WSL and PostgreSQL is on Windows, **network configurations** must be set up properly to enable smooth communication between these components.\n\n### 🛡️ Why Use Kong JWT Plugin?\nKong is an API Gateway that sits in front of our services to provide **security, traffic control, and observability**. By using Kong, we achieve:  \n- **Decoupled Authentication Logic** – JWT authentication is handled at the gateway level, eliminating the need to modify Spring Boot code.\n- **Centralized Authentication \u0026 Security** – Kong manages authentication for multiple services without changing backend code.\n- **Scalability \u0026 Extensibility** – Easily integrate plugins like rate limiting, logging, and request transformation.\n- **Improved Performance** – JWT validation is done at Kong before reaching the backend, reducing unnecessary load.\n\n### 💾 Why Use Kong in DB-Backed Mode?\nKong strengthens API security by:  \n- **Dynamic Configuration** – Services, routes, and plugins can be configured dynamically via Kong Admin API without restarting Kong.\n- **Scalability** – Stores configurations in PostgreSQL, making it easy to scale across multiple Kong instances.\n- **Better Management** – Admin API allows real-time monitoring and adjustments without touching YAML files.\n\n### 🖧 Network Configuration Requirement\nSince Kong runs in WSL and PostgreSQL is on Windows, we need to:  \n- Allow **PostgreSQL connections** from WSL.\n- Retrieve **WSL IP address** and configure PostgreSQL to accept external connections.\n- Update `pg_hba.conf` and `postgresql.conf` for proper authentication\n\n---\n\n## 🤖 Tech Stack\nThe technology used in this project are:  \n- `Spring Boot Starter Web` – Used to build RESTful APIs for managing department data\n- `Kong API Gateway` – JWT Plugin enables token-based authentication without modifying backend logic.\n- `PostgreSQL` – Stores Kong configurations (services, routes, plugins) in a database\n- `Lombok` – Reducing boilerplate code\n- `WSL (Windows Subsystem for Linux)` – Environment to run Kong on Windows \n---\n\n## 🏗️ Project Structure\nThe project is organized into the following package structure:  \n```bash\njwt-auth-with-kong/\n│── src/main/java/com/yoanesber/jwt_auth_with_kong/\n│   ├── 📂controller/            # Contains REST controllers that handle HTTP requests and return responses\n│   ├── 📂entity/                # Contains entity classes\n│   ├── 📂service/               # Business logic layer\n│   │   ├── 📂impl/              # Implementation of services\n```\n---\n\n## ⚙ Environment Configuration\nConfiguration values are stored in `.env.development` and referenced in `application.properties`.  \nExample `.env.development` file content:  \n```properties\n# Application properties\nAPP_PORT=8081\nSPRING_PROFILES_ACTIVE=development\n```\n\nExample `application.properties` file content:\n```properties\n# Application properties\nspring.application.name=jwt-auth-with-kong\nserver.port=${APP_PORT}\nspring.profiles.active=${SPRING_PROFILES_ACTIVE}\n```\n---\n\n## 🛠️ Installation \u0026 Setup\nThis project is built and developed on **Windows**, using **WSL (Windows Subsystem for Linux) to run Kong**, while **PostgreSQL is installed on Windows**. This setup allows seamless communication between Kong (running in WSL) and the PostgreSQL database on Windows.  \n\nA step by step series of examples that tell you how to get a development env running.  \n\n### A. Clone the Project Repository\n1. Ensure you have **Git installed on your Windows** machine, then clone the repository to your local environment:  \n```bash\ngit clone https://github.com/yoanesber/Spring-Boot-JWT-Auth-Kong.git\n```\n\n2. Navigate to the project folder:  \n```bash\ncd Spring-Boot-JWT-Auth-Kong\n```\n\n3. Run the application locally:  \n```bash\nmvn spring-boot:run\n```\n\n4. The API will be available at:  \n```bash\nhttp://localhost:8081/\n```\n\n### B. Ensure WSL (Windows Subsystem for Linux) is Installed on Windows\nWSL (Windows Subsystem for Linux) is not enabled by default on Windows. You need to enable it manually before you can install and use it. Follow [How to install Linux on Windows with WSL](https://learn.microsoft.com/en-us/windows/wsl/install).  \n\n### C. Ensure PostgreSQL is Installed on Windows\nMake sure **PostgreSQL is installed and running on your Windows** machine at port `5432`, as Kong will use it in **DB-Backed Mode**.  \n\n### D. Install Kong in WSL (Windows Subsystem for Linux)\n1. Set up the Kong APT repository by following [Install Kong Gateway on Ubuntu](https://docs.konghq.com/gateway/latest/install/linux/ubuntu/). If you are using a different release, replace `noble` with `$(lsb_release -sc)` or the release name in the command below. To check your release name, run `lsb_release -sc`.  \n```bash\ncurl -1sLf \"https://packages.konghq.com/public/gateway-39/gpg.B9DCD032B1696A89.key\" |  gpg --dearmor | sudo tee /usr/share/keyrings/kong-gateway-39-archive-keyring.gpg \u003e /dev/null\ncurl -1sLf \"https://packages.konghq.com/public/gateway-39/config.deb.txt?distro=ubuntu\u0026codename=noble\" | sudo tee /etc/apt/sources.list.d/kong-gateway-39.list \u003e /dev/null\n```\n**Note**: These two commands are used in WSL (Ubuntu) to add Kong Gateway's official package repository to your system. The first command, downloads the GPG key from Kong's official repository. The GPG key is used to verify the authenticity of Kong's package repository, preventing security risks. The second one, adds Kong’s official package repository to your system so you can install Kong.  \n\n2. Update the repository:  \n```bash\nsudo apt-get update\n```\n**Note**: This command is used in Ubuntu (including WSL) to update the package lists from all configured repositories. This ensures you get the latest package versions before installing new software.  \n\n3. Install Kong:  \n```bash\nsudo apt-get install -y kong-enterprise-edition=3.9.1.1\n```\n**Note**: This command installs a specific version of Kong Enterprise Edition (3.9.1.1) in WSL (Ubuntu).  \n\n4. Ensure Kong is installed:  \n```bash\nkong version\n```\n\n\n### E. Ensure Kong in WSL Can Communicate with PostgreSQL in Windows\n1. Allow PostgreSQL Port 5432 in Windows Firewall (Create a new inbound rule to allow traffic on port 5432):  \n- Open **\"Windows Defender Firewall with Advanced Security\"**\n- Go to **\"Inbound Rules\"**\n- Click **\"New Rule\"** → Select **\"Port\"** → Click **\"Next\"**\n- Choose **\"TCP\"** and enter **\"5432\"**, then click **\"Next\"**\n- Select **\"Allow the Connection\"** → Click **\"Next\"**\n- Apply to **\"Private\"** and **\"Public\"** networks → Click **\"Next\"**\n- Name it **\"PostgreSQL 5432\"** and click **\"Finish\"**\n\n**Note**: By default, Windows Firewall blocks external connections. Since Kong is running inside WSL and PostgreSQL is installed on Windows, they need to communicate over the network. By allowing port 5432 in Windows Firewall, you ensure that WSL can connect to PostgreSQL running on Windows.\n\n2. Find Your WSL IP Address, run the following command in WSL:  \n```bash\nip addr show eth0 | grep 'inet ' | awk '{print $2}' | cut -d'/' -f1\n```\n\nExample output:  \n```bash\n192.168.1.101\n```\n\n3. Allow Windows PostgreSQL to Accept External Connections  \n- Navigate to `C:\\Program Files\\PostgreSQL\\\u003cversion\u003e\\data`.\n- Before making any changes, create a backup of your `postgresql.conf` and `pg_hba.conf` file.\n- Open `postgresql.conf` using Notepad as **administrator**. Edit `postgresql.conf` and find:\n```bash\nlisten_addresses = 'localhost'\n```\n\nChange it to:  \n```bash\nlisten_addresses = '*'\n```\n\n- Open `pg_hba.conf` using Notepad as **administrator**. Edit `pg_hba.conf` and add the following line at the end:  \n```bash\nhost    all             all             \u003cWSL_IP_ADDRESS\u003e/32       md5\n```\n\nfor example:  \n```bash\nhost    all             all             192.168.1.101/32       md5\n```\n- Reload PostgreSQL (Preferred Way). Open Command Prompt, Run as Admin, then execute:  \n```bash\npg_ctl reload -D \"C:\\Program Files\\PostgreSQL\\\u003cversion\u003e\\data\"\n```\n**Note**: You must either restart or reload PostgreSQL for changes in pg_hba.conf to take effect.\n\n4. Ensure WSL can communicate with PostgreSQL by running the following command in WSL:  \n```bash\npsql -h \u003cWINDOWS_IP_ADDRESS\u003e -U postgres -d postgres\n```\n**Note**: After running this, you will be prompted to fill in the password.  \n\n### F. Bootstrapping Kong Database\n1. Create a Separate User and Database for Kong  \n- Connect to PostgreSQL (from WSL or Windows Terminal)  \n```bash\npsql -h \u003cWINDOWS_IP_ADDRESS\u003e -U postgres -d postgres\n```\n\n- Then, run this scripts:  \n```sql\nCREATE DATABASE kong;\nCREATE USER kong WITH PASSWORD '\u003cPASSWORD\u003e';\nGRANT ALL ON SCHEMA public TO kong;\nGRANT ALL PRIVILEGES ON DATABASE kong TO kong;\n```\n\n2. Modify Kong’s Configuration in WSL  \n- Copy the default configuration file and edit the copied file:  \n```bash\nsudo cp /etc/kong/kong.conf.default /etc/kong/kong.conf\nsudo nano /etc/kong/kong.conf\n```\n**Note**: However, `kong.conf.default` should not be modified directly. Instead, we copy it to create a new configuration file.  \n\n- Find and modify the following lines:  \n```bash\ndatabase = postgres\npg_host = \u003cWINDOWS_IP_ADDRESS\u003e\npg_port = 5432\npg_user = kong\npg_password = \u003cPASSWORD\u003e\npg_database = kong\n```\n**Note**: Replace `\u003cWINDOWS_IP_ADDRESS\u003e` with **your Windows PostgreSQL IP** and `\u003cPASSWORD\u003e` with your actual PostgreSQL credentials.  \n\n- Save and exit Nano: Press `CTRL+X`, then **Y**, then **Enter**  \n\n3. Bootstrap the database  \n- Migrate Kong Database  \n```bash\nsudo kong migrations bootstrap -c /etc/kong/kong.conf\n```\n\n4. Start Kong Service  \n```bash\nkong start --conf /etc/kong/kong.conf\n```\n\n5. Verify Kong is Running in WSL  \n```bash\ncurl -i http://localhost:8001\n```\n\n### G. Register Spring Services into Kong\n**Kong Ports**:  \n- `8000`: Kong Proxy (HTTP) → Used to forward API requests\n- `8001`: Kong Admin API (HTTP) → Used for managing services, routes, plugins\n\n1. Register Your API as a Kong Service in WSL  \n- Run the following command in WSL (replace the values accordingly):  \n```bash\ncurl -i -X POST http://localhost:8001/services --data \"name=department-service\" --data \"url=http://\u003cWINDOWS_IP_ADDRESS\u003e:\u003cRUNNING_APP_PORT\u003e/api/v1/departments\"\n```\n**Note**: This registers a new service in Kong called `\"department-service\"` and stores the configuration in Kong's database.  \n\n2. Create a Route for `/api/v1/departments`  \n- Now, expose the API by defining a route:  \n```bash\ncurl -i -X POST http://localhost:8001/services/department-service/routes --data \"name=department-route\" --data \"paths[]=/api/v1/departments\"\n```\n**Note**: This tells Kong that requests to `\"http://localhost:8000/api/v1/departments\"` will now be proxied to your Spring Boot API `\"http://\u003cWINDOWS_IP_ADDRESS\u003e:\u003cRUNNING_APP_PORT\u003e/api/v1/departments\"`.  \n\n3. Test the API via Kong:  \n```bash\ncurl -i http://localhost:8000/api/v1/departments\n```\n\n4. Kong forwards it to:  \n```bash\nhttp://\u003cWINDOWS_IP_ADDRESS\u003e:\u003cRUNNING_APP_PORT\u003e/api/v1/departments\n```\n\n5. Spring Boot API returns the response back through Kong.  \n```bash\nHTTP/1.1 200\nContent-Type: application/json\n...\n{\"statusCode\":200,\"timestamp\":\"2025-03-24T11:11:52.286996700Z\",\"message\":\"Departments retrieved successfully\",\"data\":...}\n```\n\n\n### H. Enable the JWT Plugin on Specific Service\n1. Enable the JWT Plugin  \n- First, you need to enable the **JWT authentication plugin** on your registered Kong service (e.g., department-service). Run the following command in **WSL**:  \n```bash\ncurl -X POST http://localhost:8001/services/department-service/plugins --data \"name=jwt\"\n```\n\n**Note**: `name=jwt` → This enables JWT authentication for the department-service. Kong will now require **a valid JWT token** for every request to this service.  \n\n\n2. View Applied Plugins  \n- To check if the **jwt plugin** is successfully applied, run:  \n```bash\ncurl -i http://localhost:8001/plugins\n```\n\n3. Create a Consumer in Kong  \n- A **consumer** in Kong represents a client (user or application) that will use the API. Run the following command to create a consumer named `channel1`:  \n```bash\ncurl -X POST http://localhost:8001/consumers --data \"username=channel1\"\n```\n\n**Note**: This registers a new consumer with username `channel1`. The consumer will be assigned a JWT credential to authenticate API requests.  \n\n4. Generate JWT Credentials for the Consumer  \n- Now, you need to create JWT credentials for `channel1`:  \n```bash\ncurl -i -X POST http://localhost:8001/consumers/channel1/jwt\n```\nResponse example:  \n```json\n{\n  \"created_at\": 1742920551,\n  \"algorithm\": \"HS256\",\n  \"tags\": null,\n  \"id\": \"e3b517ef-c4fb-4fa9-9dc3-311fafa7e332\",\n  \"secret\": \"F6gGrmGLi7VLpoaJNDUVztjssptmj23q\",\n  \"rsa_public_key\": null,\n  \"consumer\": {\n    \"id\": \"29a3b728-19f7-486c-b02b-33b3f70a5e5d\"\n  },\n  \"key\": \"xBSCWsI6qJLBMuyv3s7OQVuLU5J7EIEa\"\n}\n```\n\n**Note**: Key (`key`) → This will be used as the JWT `iss` (issuer). Secret (`secret`) → Used to sign JWT tokens. **Keep the `secret` safe**, as it will be used to sign JWTs.  \n\n5. Create and Sign a JWT Token  \nTo authenticate API requests, a **JWT Token** must be generated and signed. One option is to use **JWT debugger** at **[jwt.io](https://jwt.io/)** to manually generate tokens for testing. Alternatively, a JWT provider service can be used to issue tokens dynamically.  \nThe claims must contain the secret’s key field in the configured claim. That claim is `iss` (issuer field) by default. Set its value to our previously created credential’s `key`. The claims may contain other values.  \n\n##### Example JWT Structure\n**Header (Algorithm \u0026 Token Type)**  \n```json\n{\n  \"alg\": \"HS256\",\n  \"typ\": \"JWT\"\n}\n```\n\n**Payload (Data)**  \n```json\n{\n    \"iss\": \"xBSCWsI6qJLBMuyv3s7OQVuLU5J7EIEa\",\n    \"username\": \"channel1\",\n    \"iat\": 1711800000,\n    \"exp\": 1711836000\n}\n```\n\n**Sign JWT (Secret)**  \n```bash\nF6gGrmGLi7VLpoaJNDUVztjssptmj23q\n```\n\n**JSON Web Token Response**  \n```bash\neyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJ4QlNDV3NJNnFKTEJNdXl2M3M3T1FWdUxVNUo3RUlFYSIsInVzZXJuYW1lIjoiY2hhbm5lbDEiLCJpYXQiOjE3MTE4MDAwMDAsImV4cCI6MTcxMTgzNjAwMH0.YuTP87HXLHcXRI1JY1VIC8l89uVSSX5_0IvWTTntQWc\n```\n\n6. Test the API with JWT Token via Kong  \nOnce the JWT token is generated, send a request to your API through Kong:  \n\n```bash\ncurl -i -X GET http://localhost:8000/api/v1/departments -H \"Authorization: Bearer \u003cYOUR_JWT_TOKEN\u003e\"\n```\n\n##### Expected Response:\n- If the token is **valid**, Kong will forward the request to your Spring Boot API.\n- If the token is invalid, Kong will return:\n```json\n{\n  \"message\": \"Invalid signature\"\n}\n```\n- If the token is missing, Kong will return:\n```json\n{\n  \"message\": \"Unauthorized\"\n}\n```\n- If the claim iss field (`key`) is invalid, Kong will return:\n```json\n{\n  \"message\": \"No credentials found for given 'iss'\"\n}\n```\n\n---\n\n## 🔗 Related Repositories\n- Rate Limit with Kong GitHub Repository, check out [Spring Boot Department API with Kong API Gateway \u0026 Rate Limiting](https://github.com/yoanesber/Spring-Boot-Rate-Limit-Kong).\n- REST API with JWT Authentication Repository, check out [Netflix Shows REST API with JWT Authentication](https://github.com/yoanesber/Spring-Boot-JWT-Auth-PostgreSQL).\n- Form-Based Authentication Repository, check out [Spring Web Application with JDBC Session](https://github.com/yoanesber/Spring-Boot-JDBC-Session).","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fyoanesber%2Fspring-boot-jwt-auth-kong","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fyoanesber%2Fspring-boot-jwt-auth-kong","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fyoanesber%2Fspring-boot-jwt-auth-kong/lists"}