Skip to content

nurassul/springsecurity-test

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

3 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

README.md

Spring Security + JWT Test Project

A test Spring Boot application demonstrating authentication and authorization using Spring Security 6 with JWT (JSON Web Token) integration.

πŸ“‹ Project Overview

This project is a complete example of implementing Spring Security in a modern Spring Boot 4 application with JWT-based authentication. It includes user management, secure endpoints, and token-based authorization.

πŸ› οΈ Technology Stack

  • Java 21 β€” Latest LTS version
  • Spring Boot 4.0.0 β€” Modern Spring framework
  • Spring Security 6 β€” Authentication & authorization
  • JWT (JJWT 0.12.6) β€” Token-based authentication
  • MapStruct 1.5.5 β€” DTO-to-Entity mapping
  • Lombok β€” Boilerplate code reduction
  • PostgreSQL β€” Relational database
  • Maven β€” Dependency management

πŸ“ Project Structure

springsecurity-test/
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ main/java/com/project/testsecurity/
β”‚   β”‚   β”œβ”€β”€ entity/
β”‚   β”‚   β”‚   └── User.java
β”‚   β”‚   β”œβ”€β”€ dto/
β”‚   β”‚   β”‚   └── UserDto.java
β”‚   β”‚   β”œβ”€β”€ mapper/
β”‚   β”‚   β”‚   └── UserMapper.java
β”‚   β”‚   β”œβ”€β”€ service/
β”‚   β”‚   β”‚   └── impl/
β”‚   β”‚   β”‚       └── UserServiceImpl.java
β”‚   β”‚   └── TestSecurityApplication.java
β”‚   └── test/
β”œβ”€β”€ pom.xml
└── README.md

Key Components

Entity Layer (entity/User.java)

@Entity
@Table(name = "users")
@Getter
@Setter
@RequiredArgsConstructor
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.UUID)
    @Column(name = "user_id")
    private UUID userId;
    
    @Column(name = "first_name")
    private String firstName;
    
    @Column(name = "last_name")
    private String lastName;
    
    @Column(name = "email")
    private String email;
    
    @Column(name = "password")
    private String password;
}

DTO Layer (dto/UserDto.java)

@Data
public class UserDto {
    String userId;
    String firstName;
    String lastName;
    String email;
    String password;
}

Mapper Interface (mapper/UserMapper.java)

MapStruct-based interface for converting between User entity and UserDto:

@Mapper(componentModel = MappingConstants.ComponentModel.SPRING,
        unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface UserMapper {
    UserDto toDto(User user);
    User toEntity(UserDto dto);
}

βš™οΈ Configuration

Dependencies (pom.xml)

Key dependencies included:

  • spring-boot-starter-security β€” Spring Security framework
  • spring-boot-starter-data-jpa β€” JPA/Hibernate ORM
  • spring-boot-starter-webmvc β€” Web MVC support
  • jjwt-* (api, impl, jackson) β€” JWT token creation and validation
  • mapstruct + mapstruct-processor β€” DTO mapping
  • lombok β€” Code generation
  • postgresql β€” Database driver

Maven Compiler Configuration

Ensures proper annotation processing for Lombok and MapStruct:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.11.0</version>
    <configuration>
        <source>21</source>
        <target>21</target>
        <annotationProcessorPaths>
            <path>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
            </path>
            <path>
                <groupId>org.mapstruct</groupId>
                <artifactId>mapstruct-processor</artifactId>
                <version>1.5.5.Final</version>
            </path>
        </annotationProcessorPaths>
    </configuration>
</plugin>

πŸš€ Getting Started

Prerequisites

  • Java 21 or higher
  • Maven 3.8+
  • PostgreSQL 12+ (for production)
  • Git

Installation

  1. Clone the repository:
git clone https://github.com/nurassul/springsecurity-test.git
cd springsecurity-test
  1. Configure database (application.properties or application.yml):
spring.datasource.url=jdbc:postgresql://localhost:5432/springsecurity_db
spring.datasource.username=postgres
spring.datasource.password=your_password
spring.jpa.hibernate.ddl-auto=update
  1. Build the project:
mvn clean install
  1. Run the application:
mvn spring-boot:run

The application will start on http://localhost:8080

πŸ” Security Features

Authentication

  • User registration with encrypted passwords
  • Login endpoint returning JWT token
  • Token validation for protected endpoints

Authorization

  • Role-based access control (RBAC)
  • JWT-based stateless authentication
  • Secure password encryption

πŸ”§ Common Issues & Solutions

Bean Not Found Error

Error: Parameter 1 of constructor required a bean of type 'UserMapper' that could not be found

Solution: Ensure MapStruct processor is configured correctly in pom.xml:

  • Add mapstruct-processor dependency
  • Include it in annotationProcessorPaths in maven-compiler-plugin
  • Rebuild project: mvn clean rebuild

JWT Token Issues

  • Verify JJWT version compatibility with Spring Boot 4.0.0
  • Check JWT secret key configuration
  • Validate token expiration settings

πŸ“š API Endpoints (Example)

Method Endpoint Description
POST /api/auth/register Register new user
POST /api/auth/login Login & get JWT token
GET /api/users/{id} Get user by ID (requires auth)
PUT /api/users/{id} Update user (requires auth)
DELETE /api/users/{id} Delete user (requires auth)

πŸ§ͺ Testing

Run tests with Maven:

mvn test

Tests include:

  • Unit tests for services
  • Integration tests with Spring Security
  • JWT token validation tests

πŸ“ Configuration Files

Application Properties

Create src/main/resources/application.properties:

# Server Configuration
server.port=8080

# Database
spring.datasource.url=jdbc:postgresql://localhost:5432/springsecurity_db
spring.datasource.username=postgres
spring.datasource.password=password
spring.datasource.driver-class-name=org.postgresql.Driver

# JPA/Hibernate
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=false
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect

# JWT Configuration
jwt.secret.key=your-super-secret-key-change-in-production
jwt.expiration=86400000

# Security
spring.security.user.name=admin
spring.security.user.password=admin123

🀝 Contributing

Contributions are welcome! Please follow these steps:

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit changes (git commit -m 'Add amazing feature')
  4. Push to branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

πŸ“„ License

This project is licensed under the MIT License β€” see the LICENSE file for details.

πŸ‘€ Author

nurassul β€” GitHub: @nurassul

πŸ“ž Support

For issues and questions, please open an issue on the GitHub repository.


Happy Coding! πŸŽ‰

About

Making test project spring security + JWT

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages