This project is a Spring Boot application that demonstrates how to implement session-based authentication using Spring Security. It uses Redis as the session store, allowing for scalable and distributed session management.
- User Authentication: Secure user registration and login.
- Session Management: Utilizes Spring Session with Redis to manage user sessions.
- Role-Based Access Control (RBAC): Endpoints are secured based on user roles (e.g.,
ROLE_USER). - Custom Authentication Filter: Implements a custom
LoginFilterfor handling authentication logic. - Centralized Security Configuration: All security rules, URL permissions, and filter chains are configured in
SecurityConfig.
- Framework: Spring Boot 3
- Language: Java 17
- Authentication: Spring Security
- Database: Spring Data JPA, MySQL
- Session Store: Spring Session Data Redis, Redis
- Build Tool: Gradle
- Java 17 or higher
- Gradle
- Docker and Docker Compose (Optional, for running DB/Redis)
This project includes a docker-compose.yml file to easily set up the required MySQL and Redis services.
-
Start the services: Run the following command in the root directory of the project:
docker-compose up -d
This will start MySQL on port
3306and Redis on port6379in the background. -
Verify: The credentials and database name in
docker-compose.ymlare pre-configured to match the settings insrc/main/resources/application.yml. No further configuration is needed if you use this method.
If you are not using Docker, ensure MySQL and Redis are running and accessible.
-
Database and Redis: Open the
src/main/resources/application.ymlfile and update the following properties to match your local environment:spring.datasource.urlspring.datasource.usernamespring.datasource.passwordspring.data.redis.hostspring.data.redis.port
-
Database Schema: The application uses
spring.jpa.hibernate.ddl-auto: update, which will automatically update the schema based on the entity classes (UserEntity,Role). Ensure you have a database namedsession(or as configured in the datasource URL).
-
Build the project:
./gradlew build
-
Run the application:
./gradlew bootRun
The application will start on the default port
8080.
| Method | Path | Description | Authentication |
|---|---|---|---|
POST |
/user |
Registers a new user. | Not Required |
POST |
/session |
Authenticates a user and creates a session. | Not Required |
DELETE |
/session |
Logs out the current user and invalidates the session. | Required |
GET |
/ |
A sample protected endpoint that requires ROLE_USER. |
Required |
1. User Registration (POST /user)
{
"username": "testuser",
"password": "password123"
}2. User Login (POST /session)
{
"username": "testuser",
"password": "password123"
}