Skip to content

YoungDev7/chatapp-spring-backend

Repository files navigation

Chat Application - Backend

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.

Application Architecture

πŸš€ Technologies Used

  • 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

πŸ“‹ Features

  • 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

πŸ—οΈ Project Structure

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

πŸ› οΈ Installation & Setup

Prerequisites

  • Java 22
  • Maven 3.6+
  • MySQL 8.0+
  • Docker & Docker Compose (for containerized setup)

Development Setup

  1. 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
  2. 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;
  3. 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.properties with 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
  4. Build the Application

    # Clean and install dependencies
    ./mvnw clean install
    
    # Or using Maven
    mvn clean install
  5. Build and Run (Local)

    # Using Maven wrapper
    ./mvnw spring-boot:run
    
    # Or using Maven
    mvn spring-boot:run

πŸ‹ Docker Setup (Recommended)

Development Environment

# From the backend repository directory
docker-compose -f docker-compose.dev.yml up --build

This will start:

  • Backend application with hot reload
  • Frontend application with hot reload
  • MySQL database
  • All services networked together

Production Environment

# From the backend repository directory
docker-compose up --build

This will start:

  • Optimized backend application
  • Optimized frontend application (built and served via Nginx)
  • MySQL database

Verify Installation

  • Backend API: http://localhost:8080
  • Frontend App: http://localhost:5173 (dev) or http://localhost:3000 (prod)
  • Database: localhost:3306

πŸ“Š Database Schema

Users Table

CREATE TABLE user (
    uid VARCHAR(36) PRIMARY KEY,
    name VARCHAR(255) UNIQUE,
    password VARCHAR(255),
    email VARCHAR(255) UNIQUE
);

Messages Table

CREATE TABLE message (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    text TEXT,
    user_uid VARCHAR(36),
    FOREIGN KEY (user_uid) REFERENCES user(uid)
);

Tokens Table

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)
);

πŸ” Authentication & Security

JWT Configuration

  • Access Token Expiration: 1 hour (configurable)
  • Refresh Token Expiration: 7 days (configurable)
  • Secret Key: Configurable via environment variables

Security Features

  • 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

Authentication Flow

  1. User registers with POST /api/v1/auth/register
  2. User logs in with POST /api/v1/auth/authenticate
  3. JWT access token returned in response, refresh token set as HTTP-only cookie
  4. Access token used in Authorization header for API authentication
  5. Refresh token automatically sent via cookie to obtain new access tokens
  6. User logs out with POST /api/v1/auth/logout to revoke all tokens

πŸ“‘ API Endpoints

Authentication

  • POST /api/v1/auth/authenticate - User login with email and password
  • POST /api/v1/auth/register - User registration
  • POST /api/v1/auth/refresh - Refresh access token using refresh token
  • GET /api/v1/auth/validateToken - Validate current access token
  • POST /api/v1/auth/logout - User logout (revokes all tokens)

Messages

  • GET /api/v1/messages - Get all messages
  • WebSocket endpoint: /app/chat - Send message
  • WebSocket topic: /topic/messages - Receive messages

πŸ”Œ WebSocket Configuration

Endpoints

  • Connect: /ws
  • Send Messages: /app/chat
  • Subscribe: /topic/messages

Message Flow

  1. Client connects to WebSocket endpoint
  2. Client sends message to /app/chat
  3. Server processes via MessageController
  4. Server broadcasts to /topic/messages
  5. All connected clients receive the message

βš™οΈ Configuration

Environment Variables

All configuration is managed through environment variables defined in .env and application-dev.properties

CORS Configuration

Configured in CorsConfig.java to allow frontend requests.

Test Configuration

  • H2 in-memory database for testing
  • Test profiles with separate configuration
  • MockJwtService in test_util/MockJwtService.java for authentication testing
  • Integration tests for controllers
  • Unit tests for services

Test Structure

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

πŸ“Š Logging

Logging Architecture

The application uses a filter-based logging approach with MDC (Mapped Diagnostic Context)

LoggerUtil

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

LoggingFilter

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

UserContextFilter

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

Logging Configuration

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

πŸ”§ Database Migrations

Flyway Migrations

Located in src/main/resources/db/migration/:

  • V1__Create_user_table.sql - Initial user table
  • V2__Create_message_table.sql - Message table
  • V3__Create_token_table.sql - Token table

πŸš€ Deployment

Docker Deployment (Recommended)

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

Manual Deployment

# Create JAR file
./mvnw clean package

# Run JAR
java -jar target/chatapp-0.0.1-SNAPSHOT.jar

πŸ›‘οΈ Security Considerations

Implemented Security Features

  • Password hashing with BCrypt
  • JWT token expiration and refresh rotation
  • Request/response logging

Additional Security Notes

  • All sensitive configuration is externalized to environment variables
  • Database credentials are not hardcoded
  • JWT secret keys should be properly generated and secured in production

πŸ› Troubleshooting

Common Issues

  1. Database Connection Errors

    • Verify MySQL is running (check with docker-compose ps)
    • Check connection parameters in .env
    • Ensure database exists and user has permissions
  2. JWT Token Issues

    • Verify JWT secret key configuration
    • Check token expiration settings
    • Clear browser cookies and try again
  3. WebSocket Connection Problems

    • Check CORS configuration in CorsConfig.java
    • Verify WebSocket endpoint mapping
    • Test with WebSocket client tools
  4. Docker Issues

    • Ensure both repositories are in the same parent directory
    • Check Docker compose file paths
    • Verify environment variables are properly set

Debug Mode

Enable debug logging in environment variables:

LOGGING_LEVEL_ORG_SPRINGFRAMEWORK_WEB=DEBUG
LOGGING_LEVEL_ORG_SPRINGFRAMEWORK_SECURITY=DEBUG
LOGGING_LEVEL_COM_CHATAPP_CHATAPP=DEBUG

πŸ“š Documentation

System Architecture & Diagrams

Authentication Flow

Authentication Sequence Step-by-step authentication process from login to token generation

Class Diagram

Class Diagram Entity relationship and class structure showing the domain model

JWT Authentication Flow

JWT Authentication Detailed JWT token validation and authentication filter chain

Message Flow

Message Flow Sequence Real-time messaging flow through WebSocket connections

Token Refresh Flow

Token Refresh Sequence Token refresh mechanism and authentication flow

Use Case Diagram

Use Case Diagram User interactions and system capabilities overview

πŸ”— Related Projects

πŸ“„ License

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.

About

real-time chat application (backend)

Resources

Stars

Watchers

Forks

Packages

No packages published