Skip to content

Secure Java server: auth, token refresh, WebSockets. Uses Spring Security and Java WebSocket API for real-time, authorized access. JWTs refresh tokens, boosting security. HTTPS and input validation ensure system integrity.

License

Notifications You must be signed in to change notification settings

MrDay2Day/Java-Spring-Web-Server

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

15 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Modern Java Spring Web Server Architecture πŸš€

Enterprise-grade Authentication, Real-time Communication & Multi-Database Solution

Java Spring Boot Spring Security Maven License GitHub

Welcome to the definitive implementation of a production-ready Java Spring Web Server that solves the complex challenges of modern web application development. This project demonstrates industry best practices for security, stateless authentication, and bidirectional communication.

Core Capabilities πŸ’ͺ

  • Stateless Authentication with JWT πŸ” - Implements the OAuth 2.0 authorization framework using JSON Web Tokens for secure, scalable authentication
  • Defense-in-Depth Security πŸ›‘οΈ - Protects authentication tokens with HTTP-only secure cookies, mitigating XSS vulnerabilities
  • Seamless Session Management ⚑ - Transparent token refresh mechanism maintains user sessions without disrupting experience
  • Polyglot Persistence πŸ’Ύ - Configurable connections to multiple database systems (PostgreSQL, MySQL) with transaction support
  • Real-time Bidirectional Communication πŸ“‘ - Full WebSocket implementation for instant data exchange and notifications
  • Production-Ready Architecture πŸ—οΈ - Built on Spring Boot's enterprise-grade foundation with comprehensive security controls

Technical Stack πŸ“š

  • Java 17+ β˜• - Modern language features including records, pattern matching, and enhanced switch expressions
  • Spring Boot 3.x πŸƒ - Streamlined application bootstrapping and configuration
  • Spring Security πŸ”’ - Comprehensive security framework with secure defaults
  • Spring WebFlux βš›οΈ - Reactive programming model for highly concurrent applications
  • Spring Data JPA πŸ“Š - Advanced ORM with sophisticated query capabilities
  • JWT Library 🎟️ - Industry-standard JWT implementation with robust signature verification
  • Spring WebSocket πŸ”Œ - Enterprise-grade WebSocket implementation with STOMP messaging
  • Hibernate πŸ—„οΈ - Feature-rich JPA provider with extensive customization options

Getting Started 🏁

Prerequisites

  • JDK 17+
  • Maven 3.8+
  • PostgreSQL/MySQL instance

Quick Setup

  1. Clone & Navigate: πŸ“‚

    git clone https://github.com/MrDay2Day/spring-advanced-webserver.git
    cd spring-advanced-webserver
  2. Configure Your Environment: βš™οΈ Create an application-dev.properties file based on the template below:

    # Environment Variables
    
    # Spring Server Variables
    
    server.port=3077
    server.tomcat.max-http-header-size=1048576
    
    # JWT Variables
    
    jwt.secret=your-very-long-and-secure-secret-key
    jwt.refresh.secret=your-very-long-and-secure-secret-key-for-refresh
    jwt.websocket.secret=your-very-long-and-secure-secret-key-for-websocket
    
    jwt.cookie.name=jwtToken
    jwt.expiration.seconds=30
    
    jwt.cookie.refresh.name=jwtRefreshToken
    jwt.expiration.refresh.seconds=5184000
    
    jwt.cookie.secret=this_is_a_secure_string_to_sign_cookies_from_this_server
    
    # PostGreSQL Variables
    
    postgresql.conn.host=postgresql_host
    postgresql.conn.database=database
    postgresql.conn.username=username
    postgresql.conn.password=password
    
    # MySQL Variables
    
    mysql.conn.host=mysql_host
    mysql.conn.database=database
    mysql.conn.username=username
    mysql.conn.password=password
    
    # HikariCP (Connection Pool) Settings (Optional but Recommended)
    spring.datasource.hikari.maximum-pool-size=10
    spring.datasource.hikari.minimum-idle=2
    spring.datasource.hikari.idle-timeout=30000
    spring.datasource.hikari.connection-timeout=30000
  3. Build & Run: πŸ› οΈ

    mvn clean install
    mvn spring-boot:run -Dspring-boot.run.profiles=dev
  4. Verify Installation: βœ… The server will start at http://localhost:3077

API Reference πŸ“˜

Authentication Endpoints πŸ”‘

Endpoint Method Description Request Body Response
/auth/register POST Create new user account {"username":"user","password":"pass","email":"[email protected]"} User details with 201 status
/auth/login POST Authenticate user {"username":"user","password":"pass"} Sets HTTP-only cookies, returns user profile
/auth/logout POST End user session None Clears auth cookies, returns 200 status
/auth/refresh-websocket-token GET Generate WebSocket token None (requires auth cookie) {"token":"ws-jwt-token"}

Secure API Endpoints πŸ”’

Endpoint Method Description Authentication
/secure/get GET Test authenticated access Required
/secure/send-websocket-message POST Send real-time message Required

WebSocket Communication πŸ“‘

Connect to the WebSocket endpoint with your authentication token:

ws://localhost:3077/ws?token={your-ws-token}

Send a test message through the REST API:

POST /secure/send-websocket-message

{
  "userId": "3",
  "message": "Real-time notification test"
}

Architecture Deep-Dive πŸ”

Authentication Flow πŸ”„

  1. Registration: User credentials are securely hashed with BCrypt before storage
  2. Login: Credentials verified, JWT tokens generated (access + refresh)
  3. Token Storage: JWTs stored in HTTP-only cookies with secure and SameSite flags
  4. Auto-Refresh: Interceptors transparently refresh tokens before expiration
  5. WebSocket Auth: Specialized short-lived tokens for WebSocket connections

Security Implementation πŸ›‘οΈ

  • CSRF Protection: Spring Security's CSRF token validation
  • XSS Mitigation: Content-Security-Policy headers and HTTP-only cookies
  • Input Validation: Bean Validation (JSR 380) for request payload validation
  • Rate Limiting: Custom interceptors prevent brute force attacks
  • Secure Headers: Implements OWASP recommended security headers

Database Architecture πŸ’Ύ

The multi-database configuration enables:

  • Separation of concerns (e.g., user data vs. application data)
  • Cross-database transactions with JTA when needed
  • Database-specific optimization strategies
  • Read-write splitting for high-load scenarios

WebSocket Implementation πŸ”Œ

Our WebSocket implementation provides:

  • Authenticated connections with JWT verification
  • STOMP messaging protocol for pub/sub capabilities
  • Message filtering based on user context
  • Reconnection handling with session recovery
  • Optimized broadcast capabilities for high-volume messaging

Spring Boot Essentials πŸƒ

Spring Boot revolutionizes Java web development through:

Convention Over Configuration βš™οΈ

Spring Boot eliminates boilerplate by providing sensible defaults while allowing customization where needed. This approach dramatically reduces development time and cognitive overhead.

Embedded Application Server πŸ“¦

The embedded Tomcat/Jetty/Undertow server eliminates deployment complexity and enables true "java -jar" deployment with minimal configuration.

Auto-Configuration πŸ”„

Spring Boot analyzes your classpath and automatically configures components based on detected libraries, reducing configuration to the absolute minimum.

Production-Ready Features πŸš€

Built-in actuator endpoints provide metrics, health checks, and environment information essential for production monitoring.

Dependency Management πŸ“š

Spring Boot carefully curates compatible dependency versions, eliminating "dependency hell" and ensuring components work together seamlessly.

Spring Annotation Deep-Dive πŸ”

Spring's annotation-based programming model provides clear component classification:

  • @Configuration: Classes that define beans through @Bean methods
  • @Component: Generic Spring-managed component
  • @Controller/@RestController: Web request handlers
  • @Service: Business logic encapsulation
  • @Repository: Data access components with exception translation
  • @Entity: JPA-managed database entity
  • @Autowired: Dependency injection marker (constructor injection preferred)
  • @RequestMapping/@GetMapping/@PostMapping: HTTP request mapping
  • @ExceptionHandler: Centralized exception management

Advanced Features ✨

Asynchronous Processing ⏱️

The application demonstrates Spring's @Async capabilities for background processing tasks.

Caching πŸ’¨

Strategic caching with Spring Cache and EhCache reduces database load for frequently accessed data.

Comprehensive Testing πŸ§ͺ

Includes unit, integration, and end-to-end tests with JUnit 5, Mockito, and Spring Test.

Advanced WebSocket Features πŸ“‘

  • Binary message support
  • Message compression
  • Client heartbeat monitoring
  • Session affinity for clustered deployments

Project Structure πŸ“

β”œβ”€β”€ .gitignore
β”œβ”€β”€ pom.xml
β”œβ”€β”€ README.md
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ main/
β”‚   β”‚   β”œβ”€β”€ java/
β”‚   β”‚   β”‚   └── org/
β”‚   β”‚   β”‚       └── file/
β”‚   β”‚   β”‚           β”œβ”€β”€ apiResponse/
β”‚   β”‚   β”‚           β”‚   β”œβ”€β”€ ApiResponse.java
β”‚   β”‚   β”‚           β”‚   └── HttpServletErrorResponse.java
β”‚   β”‚   β”‚           β”œβ”€β”€ controllers/
β”‚   β”‚   β”‚           β”‚   β”œβ”€β”€ AuthController.java
β”‚   β”‚   β”‚           β”‚   β”œβ”€β”€ CookieController.java
β”‚   β”‚   β”‚           β”‚   └── MainController.java
β”‚   β”‚   β”‚           β”œβ”€β”€ database/
β”‚   β”‚   β”‚           β”‚   β”œβ”€β”€ DatabaseType.java
β”‚   β”‚   β”‚           β”‚   β”œβ”€β”€ DataSourceConfig.java
β”‚   β”‚   β”‚           β”‚   β”œβ”€β”€ DatabaseConnection.java
β”‚   β”‚   β”‚           β”‚   β”œβ”€β”€ DatabaseQueryExecution.java
β”‚   β”‚   β”‚           β”‚   β”œβ”€β”€ DatabaseDynamicQueryExecution.java
β”‚   β”‚   β”‚           β”‚   └── models/
β”‚   β”‚   β”‚           β”‚       β”œβ”€β”€ User.java
β”‚   β”‚   β”‚           β”‚       └── UserPublicInfo.java
β”‚   β”‚   β”‚           β”œβ”€β”€ middleware/
β”‚   β”‚   β”‚           β”‚   β”œβ”€β”€ apiGlobals/
β”‚   β”‚   β”‚           β”‚   β”‚   └── GlobalsExceptionHandler.java
β”‚   β”‚   β”‚           β”‚   └── filters/
β”‚   β”‚   β”‚           β”‚   |   β”œβ”€β”€ FilterConfig.java
β”‚   β”‚   β”‚           β”‚   |   └── CookieFilter.java
β”‚   β”‚   β”‚           β”‚   └── interceptors/
β”‚   β”‚   β”‚           β”‚       β”œβ”€β”€ AuthInterceptor.java
β”‚   β”‚   β”‚           β”‚       β”œβ”€β”€ InterceptorConfig.java
β”‚   β”‚   β”‚           β”‚       └── MainInterceptor.java
β”‚   β”‚   β”‚           └── utils/
β”‚   β”‚   β”‚           |   β”œβ”€β”€ BcryptHashing.java
β”‚   β”‚   β”‚           |   β”œβ”€β”€ JwtUtil.java
β”‚   β”‚   β”‚           |   └── GenerateCookie.java
β”‚   β”‚   β”‚           β”œβ”€β”€ Main.java
β”‚   β”‚   β”‚           └── webSocket/
β”‚   β”‚   β”‚               β”œβ”€β”€ MainWebSocketHandler.java
β”‚   β”‚   β”‚               └── WebSocketConfig.java
β”‚   β”‚   └── resources/
β”‚   β”‚       └── application.properties
β”‚   └── test/
β”‚       └── GitIgnore.java
β”œβ”€β”€ .idea/
└── External Libraries

Roadmap πŸ—ΊοΈ

  • GraphQL API implementation βš›οΈ
  • OAuth 2.0 social login integration πŸ”‘
  • Event-driven architecture with Spring Cloud Stream ☁️
  • Kubernetes deployment manifests 🐳
  • Comprehensive monitoring with Micrometer and Prometheus πŸ“Š

Contributing πŸ‘₯

We welcome contributions! Please see our Contributing Guide for details on our development process and pull request workflow.

License πŸ“œ

This project is licensed under the MIT License - see the LICENSE file for details.


Created with ❀️ by MrDay2Day

About

Secure Java server: auth, token refresh, WebSockets. Uses Spring Security and Java WebSocket API for real-time, authorized access. JWTs refresh tokens, boosting security. HTTPS and input validation ensure system integrity.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages