A RESTful API backend for a real-time chat application built with Spring Boot. Features JWT authentication, WebSocket messaging, MySQL database integration, and comprehensive security configurations.
- Spring Boot 3.3.1 - Application framework
- Spring Security - Authentication and authorization
- Spring WebSocket - Real-time messaging
- Spring Data JPA - Database abstraction
- MySQL 8.0 - Primary database
- JWT (JJWT) - Token-based authentication
- Flyway - Database migrations
- Maven - Dependency management
- H2 - In-memory testing database
- JWT-based authentication with refresh tokens
- Real-time messaging via WebSocket/STOMP
- User registration and login
- Secure password hashing with BCrypt
- Database migrations with Flyway
- Comprehensive request logging
- CORS configuration
- Unit and integration testing
- Docker containerization
src/main/java/com/chatapp/chatapp/
βββ auth/
β βββ JwtAuthenticationFilter.java # JWT filter for requests
β βββ WebSocketAuthInterceptor.java # Websocket authentication
β βββ WebSocketHandshakeInterceptor.java # Websocket handshake
βββ config/
β βββ Config.java # General configuration & beans
β βββ CorsConfig.java # CORS configuration
β βββ SecurityConfig.java # Security configuration
β βββ WebSocketConfig.java # WebSocket configuration
βββ controller/
β βββ AuthController.java # Authentication endpoints
β βββ MessageController.java # Message endpoints & WebSocket
βββ DTO/
β βββ AuthRequest.java # Login request DTO
β βββ AuthResponse.java # Login response DTO
β βββ RegisterRequest.java # Registration request DTO
β βββ MessageRequest.java # Message request DTO
β βββ TokenInfo.java # Token transfer DTO
β βββ JwtValidationResult.java # JWT validation result DTO
βββ entity/
β βββ User.java # User entity
β βββ Message.java # Message entity
β βββ Token.java # Token entity
βββ filter/
β βββ LoggingFilter.java # Request logging filter
β βββ UserContextFilter.java # User context setup filter
βββ repository/
β βββ UserRepository.java # User data access
β βββ MessageRepository.java # Message data access
β βββ TokenRepository.java # Token data access
βββ service/
β βββ AuthService.java # Authentication services
β βββ JwtService.java # JWT token services
β βββ MessageService.java # Message services
β βββ UserService.java # User services
βββ util/
β βββ LoggerUtil.java # MDC logging utility
βββ ChatappApplication.java # Main application class
src/main/resources/
βββ application.properties # Main configuration
βββ application-docker.properties # Docker environment config
βββ application-dev.properties # Local environment config
βββ db/migration/ # Flyway database migrations
β βββ V1__Create_user_table.sql
β βββ V2__Create_message_table.sql
β βββ V3__Create_token_table.sql
src/test/java/com/chatapp/chatapp/
βββ AuthControllerTest.java # Authentication endpoint tests
βββ AuthServiceTest.java # Authentication service tests
βββ JwtServiceTest.java # JWT service tests
βββ test_util/
βββ MockJwtService.java # JWT mocking utility
Configuration Files:
βββ pom.xml # Maven dependencies & build
βββ compose.yaml # Production Docker Compose
βββ docker-compose.dev.yml # Development Docker Compose
βββ Dockerfile # Production Docker image
βββ Dockerfile.dev # Development Docker image
βββ .env.example # Environment variables template
βββ application-dev.properties.example # Dev config template
- Java 22
- Maven 3.6+
- MySQL 8.0+
- Docker & Docker Compose (for containerized setup)
-
Clone the repository structure
# Create parent directory mkdir chat-application cd chat-application # Clone both repositories git clone <backend-repository-url> chatapp-spring-backend git clone <frontend-repository-url> chatapp-react-frontend
-
Database Setup (Local Development)
CREATE DATABASE chatapp; CREATE USER 'chatapp_user'@'localhost' IDENTIFIED BY 'your_password'; GRANT ALL PRIVILEGES ON chatapp.* TO 'chatapp_user'@'localhost'; FLUSH PRIVILEGES;
-
Environment Configuration
cd chatapp-spring-backend # Copy example files cp .env.example .env cp application-dev.properties.example src/main/resources/application-dev.properties
Configure the following variables in
.env:# Database Configuration DB_URL=jdbc:mysql://localhost:3306/chatapp DB_USERNAME=chatapp_user DB_PASSWORD=your_password DB_PORT=3306 # JWT Configuration JWT_SECRET_KEY=your-256-bit-secret-key JWT_EXPIRATION=3600000 JWT_REFRESH_EXPIRATION=604800000 # CORS CORS_ALLOWED_ORIGINS= UID=1000 GID=1000 # Application Ports BACKEND_PORT=8080 FRONTEND_PORT=3000 # API URLs VITE_API_BASE_URL=http://localhost:8080/api/v1 VITE_WS_BASE_URL=http://localhost:8080/ws
Configure
application-dev.properties:Edit
src/main/resources/application-dev.propertieswith your local settings:# Development profile spring.datasource.username=chatapp_user spring.datasource.password=your_password application.security.jwt.secret-key=your-256-bit-secret-key application.security.jwt.expiration=3600000 application.security.jwt.refresh-token.expiration=604800000
Note: Generate a secure JWT secret key using:
openssl rand -base64 32
-
Build the Application
# Clean and install dependencies ./mvnw clean install # Or using Maven mvn clean install
-
Build and Run (Local)
# Using Maven wrapper ./mvnw spring-boot:run # Or using Maven mvn spring-boot:run
# From the backend repository directory
docker-compose -f docker-compose.dev.yml up --buildThis will start:
- Backend application with hot reload
- Frontend application with hot reload
- MySQL database
- All services networked together
# From the backend repository directory
docker-compose up --buildThis will start:
- Optimized backend application
- Optimized frontend application (built and served via Nginx)
- MySQL database
- Backend API:
http://localhost:8080 - Frontend App:
http://localhost:5173(dev) orhttp://localhost:3000(prod) - Database:
localhost:3306
CREATE TABLE user (
uid VARCHAR(36) PRIMARY KEY,
name VARCHAR(255) UNIQUE,
password VARCHAR(255),
email VARCHAR(255) UNIQUE
);CREATE TABLE message (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
text TEXT,
user_uid VARCHAR(36),
FOREIGN KEY (user_uid) REFERENCES user(uid)
);CREATE TABLE token (
id INT AUTO_INCREMENT PRIMARY KEY,
token VARCHAR(512),
expired BOOLEAN,
revoked BOOLEAN,
user_uid VARCHAR(36),
FOREIGN KEY (user_uid) REFERENCES user(uid)
);- Access Token Expiration: 1 hour (configurable)
- Refresh Token Expiration: 7 days (configurable)
- Secret Key: Configurable via environment variables
- Password hashing with BCrypt
- Token-based authentication with JWT
- Refresh token rotation and revocation
- CORS configuration for frontend integration
- Comprehensive request/response logging with MDC context
- Filter chain security with custom authentication filters
- User registers with
POST /api/v1/auth/register - User logs in with
POST /api/v1/auth/authenticate - JWT access token returned in response, refresh token set as HTTP-only cookie
- Access token used in Authorization header for API authentication
- Refresh token automatically sent via cookie to obtain new access tokens
- User logs out with
POST /api/v1/auth/logoutto revoke all tokens
POST /api/v1/auth/authenticate- User login with email and passwordPOST /api/v1/auth/register- User registrationPOST /api/v1/auth/refresh- Refresh access token using refresh tokenGET /api/v1/auth/validateToken- Validate current access tokenPOST /api/v1/auth/logout- User logout (revokes all tokens)
GET /api/v1/messages- Get all messages- WebSocket endpoint:
/app/chat- Send message - WebSocket topic:
/topic/messages- Receive messages
- Connect:
/ws - Send Messages:
/app/chat - Subscribe:
/topic/messages
- Client connects to WebSocket endpoint
- Client sends message to
/app/chat - Server processes via
MessageController - Server broadcasts to
/topic/messages - All connected clients receive the message
All configuration is managed through environment variables defined in .env and application-dev.properties
Configured in CorsConfig.java to allow frontend requests.
- H2 in-memory database for testing
- Test profiles with separate configuration
- MockJwtService in
test_util/MockJwtService.javafor authentication testing - Integration tests for controllers
- Unit tests for services
src/test/java/com/chatapp/chatapp/
βββ AuthControllerTest.java # Authentication endpoint tests
βββ AuthServiceTest.java # Authentication service tests
βββ JwtServiceTest.java # JWT service tests
βββ LogoutServiceTest.java # Logout service tests
βββ test_util/
βββ MockJwtService.java # JWT mocking utility
The application uses a filter-based logging approach with MDC (Mapped Diagnostic Context)
Centralized utility in LoggerUtil.java that provides:
- MDC context setup for HTTP requests (path, client IP, HTTP method)
- User context setup (username)
- Context cleanup after request processing
Request logging filter in LoggingFilter.java:
- First filter in the security chain
- Sets up MDC context at the start of each request
- Ensures proper cleanup of logging context
- Provides comprehensive request tracking
User context filter in UserContextFilter.java:
- Executes after JWT authentication
- Extracts authenticated user information
- Enriches logs with user-specific details
- Enables user-aware logging throughout the request lifecycle
All logging is configured via logback-spring.xml with support for:
- Console and file-based logging
- MDC variables in log patterns (username, path, method, clientIP)
- Different log levels per package
- Request/response tracking with correlation IDs
Located in src/main/resources/db/migration/:
V1__Create_user_table.sql- Initial user tableV2__Create_message_table.sql- Message tableV3__Create_token_table.sql- Token table
The application is fully containerized with production-ready Docker configurations:
# Production deployment
docker-compose up --build
# Development with hot reload
docker-compose -f docker-compose.dev.yml up --build# Create JAR file
./mvnw clean package
# Run JAR
java -jar target/chatapp-0.0.1-SNAPSHOT.jar- Password hashing with BCrypt
- JWT token expiration and refresh rotation
- Request/response logging
- All sensitive configuration is externalized to environment variables
- Database credentials are not hardcoded
- JWT secret keys should be properly generated and secured in production
-
Database Connection Errors
- Verify MySQL is running (check with
docker-compose ps) - Check connection parameters in
.env - Ensure database exists and user has permissions
- Verify MySQL is running (check with
-
JWT Token Issues
- Verify JWT secret key configuration
- Check token expiration settings
- Clear browser cookies and try again
-
WebSocket Connection Problems
- Check CORS configuration in
CorsConfig.java - Verify WebSocket endpoint mapping
- Test with WebSocket client tools
- Check CORS configuration in
-
Docker Issues
- Ensure both repositories are in the same parent directory
- Check Docker compose file paths
- Verify environment variables are properly set
Enable debug logging in environment variables:
LOGGING_LEVEL_ORG_SPRINGFRAMEWORK_WEB=DEBUG
LOGGING_LEVEL_ORG_SPRINGFRAMEWORK_SECURITY=DEBUG
LOGGING_LEVEL_COM_CHATAPP_CHATAPP=DEBUG
Step-by-step authentication process from login to token generation
Entity relationship and class structure showing the domain model
Detailed JWT token validation and authentication filter chain
Real-time messaging flow through WebSocket connections
Token refresh mechanism and authentication flow
User interactions and system capabilities overview
- Frontend Repository - React frontend application
This project is licensed under the MIT License.
Note: This backend is designed to work with the corresponding React frontend. Both applications are orchestrated using Docker Compose for seamless development and deployment.
