This project is a demonstration of implementing JWT Authentication within a Hexagonal Architecture using Spring Boot. It is a fork of spring-demo-jwt-auth, re-structured to clearly separate business logic from external frameworks and concerns.
The goal is to showcase a robust, maintainable, and testable approach to authentication by applying the principles of Hexagonal Architecture (Ports & Adapters).
- About the Project
- Built With
- Architecture Overview
- Getting Started
- Usage
- Project Structure
- Roadmap
- Contributing
- License
- Contact
This repository serves as a practical example for developers looking to understand how to structure a Spring Boot application with Hexagonal Architecture while incorporating a common real-world feature: JWT-based authentication and authorization.
Key Features:
- Hexagonal Architecture: Clean separation between domain, application, and infrastructure layers.
- JWT Authentication: Secure token-based authentication flow.
- Spring Boot: Leverages Spring Security and other Spring ecosystem projects.
- Dockerized Database: Easy setup with
docker-compose.ymlfor a local development database.
- Java 17+
- Spring Boot 3.0+
- Spring Security
- JSON Web Tokens (JWT)
- Maven
- Docker (for the database)
The project is structured following the Hexagonal Architecture (also known as Ports and Adapters). This pattern isolates the core domain logic from external dependencies like databases, web controllers, and security frameworks.
flowchart TD
%% Definición de Estilos (Clases)
classDef external fill:#e1e1e1,stroke:#333,stroke-width:1px,color:#333
classDef adapter fill:#d4e9ff,stroke:#0055aa,stroke-width:2px,color:#003366
classDef core fill:#e6ffed,stroke:#28a745,stroke-width:2px,color:#004400
classDef db fill:#f9f9f9,stroke:#333,stroke-width:1px,stroke-dasharray: 5 5,color:#333
subgraph "External World"
User((User / Client)):::external
DB[(Database)]:::db
end
subgraph "Infrastructure Layer (Adapters)"
direction TB
Controller[Web Controller<br/>Inbound Adapter]:::adapter
Repository[JPA Repository<br/>Outbound Adapter]:::adapter
end
subgraph "Application Core (Core)"
direction TB
InboundPort([Inbound Port<br/>AuthService Interface]):::core
AppService[Application Service<br/>Use Case Logic]:::core
OutboundPort([Outbound Port<br/>UserRepository Interface]):::core
end
%% Flujo de Request
User -->|HTTP Request + JWT| Controller
Controller -->|Call Interface| InboundPort
InboundPort --> AppService
AppService -->|Call Interface| OutboundPort
OutboundPort -->|Implementación| Repository
Repository <-->|SQL | DB
%% Flujo de Response (Opcional, para cerrar el ciclo)
DB -.->|Data| Repository
Repository -.->|Entity| OutboundPort
OutboundPort -.->|DTO| AppService
AppService -.->|Response| InboundPort
InboundPort -.->|DTO| Controller
Controller -.->|HTTP Response| User
%% Nota: Las líneas punteadas son el retorno para no saturar el dibujo
linkStyle 6,7,8,9,10 stroke:#666,stroke-width:1px,stroke-dasharray: 5 5;
- Domain / Application Layer: Contains the business logic, use cases (like
LoginUser,RegisterUser), and core models. It is completely independent of frameworks. - Adapters (Inbound/Outbound): Handle communication with the outside world.
- Inbound Adapters: REST controllers that receive HTTP requests and translate them into calls to the application layer.
- Outbound Adapters: Implementations for accessing external systems, like a JPA repository that communicates with a database.
Follow these instructions to get a copy of the project up and running on your local machine for development and testing purposes.
- Java Development Kit (JDK): Version 17 or later.
- Maven: For dependency management and building the project.
- Docker & Docker Compose: To run the database container easily.
-
Clone the repository
git clone https://github.com/alexdevzz/spring-hex-demo-jwt-auth.git cd spring-hex-demo-jwt-auth -
Start the Database (using Docker Compose) The project includes a
docker-compose.ymlfile, likely configured for a PostgreSQL or MySQL database. Run it in the background:docker-compose up -d
-
Configure Database Credentials (Optional) Check the
src/main/resources/application.propertiesfile to ensure the database URL, username, and password match your Docker setup. The defaults are usually configured to work with thedocker-compose.yml. -
Build the project
./mvnw clean package
-
Run the application
./mvnw spring-boot:run
The application will start, and you should be able to access it at
http://localhost:8080.
Once the application is running, you can interact with the authentication endpoints.
Example Endpoints:
POST /api/auth/register- Register a new user.POST /api/auth/login- Authenticate and receive a JWT token.GET /api/protected/resource- Example of a protected endpoint requiring a valid JWT in theAuthorization: Bearer <token>header.
(Note: For exact request/response formats, please refer to the source code of the controllers, as a detailed API specification was not present in the repository root.)
The project is organized into distinct modules to enforce the hexagonal architecture. A detailed breakdown can be found in proyect-structure.md.
Here is a high-level overview:
spring-hex-demo-jwt-auth/
├── .mvn/ # Maven wrapper files
├── src/
│ └── main/
│ └── java/com/example/
│ ├── application/ # Application layer (use cases, services)
│ ├── domain/ # Domain layer (entities, value objects, ports)
│ ├── infrastructure/ # Framework & adapter configurations
│ │ ├── config/ # Spring configuration (Security, Beans)
│ │ ├── adapters/ # Implementations of outbound ports (e.g., JPA)
│ │ └── ... # Other infrastructure concerns
│ └── ... # Main application class
├── docker-compose.yml # Docker setup for the database
├── pom.xml # Maven project object model
├── mvnw, mvnw.cmd # Maven wrapper scripts
├── .gitattributes # Git attributes
├── .gitignore # Git ignore rules
└── proyect-structure.md # Detailed explanation of the project structure
This project is a work-in-progress demonstration. Potential future improvements include:
- Add comprehensive unit and integration tests.
- Implement refresh token mechanism.
- Add more detailed API documentation (e.g., OpenAPI/Swagger).
- Include examples of other adapters (e.g., for a different database or messaging system).
Contributions are what make the open-source community such an amazing place to learn, inspire, and create. Any contributions you make are greatly appreciated.
If you have a suggestion that would make this better, please fork the repo and create a pull request. You can also simply open an issue with the tag "enhancement".
- Fork the Project
- Create your Feature Branch (
git checkout -b feature/AmazingFeature) - Commit your Changes (
git commit -m 'Add some AmazingFeature') - Push to the Branch (
git push origin feature/AmazingFeature) - Open a Pull Request
Distributed under the MIT License. See LICENSE file for more information. (Note: A license file was not present in the repository, but this is a common default. Please add one if you have specific licensing requirements.)
Alex Pineda (alexdevzz) - GitHub Profile
Project Link: https://github.com/alexdevzz/spring-hex-demo-jwt-auth