Skip to content

AT95BL/JWT-Authentication-Project

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

13 Commits
 
 
 
 
 
 

Repository files navigation

Spring Boot 3.x REST API Authentication with JWT

A modern, robust, and production-ready implementation of stateless user authentication and authorization using Spring Boot 3, Spring Security 6, and JSON Web Tokens (JWT).

This project demonstrates software engineering best practices by cleanly separating database layers, data containers, security middleware, and global error interceptors.


🚀 Features

  • Stateless Authentication: Completely sessionless architecture utilizing JSON Web Tokens (JWT).
  • Cryptographic Security: Secure password storage using the BCrypt hashing algorithm.
  • Mass Assignment Protection: Strict separation of data layers using specialized Data Transfer Objects (DTOs).
  • Global Exception Handling: Clean, centralized error processing producing standardized RFC 7807 (Problem Details) JSON responses.
  • Cross-Origin Resource Sharing (CORS): Pre-configured secure origin handling for standard frontend client ecosystems (e.g., React on localhost:8005).

🛠️ Architecture & Data Flow

The project acts as an automated pipeline, processing network-level HTTP requests into securely verified backend transactions:

  1. Network Level (CORS & Filters): The request hits the security boundary. The JwtAuthenticationFilter intercepts it, extracts the token from the Authorization header, and verifies its authenticity.
  2. Context Vault: If validated, the user profile is packed into an Authentication passport and stored in Spring Security's SecurityContextHolder.
  3. Data Mapping (DTOs): Incoming requests map directly to lightweight DTOs (RegisterUserDto, LoginUserDto) to protect raw JPA Entities from mass-assignment injection attacks.
  4. Service / DB Integration: The AuthenticationService orchestrates business logic (e.g., validating hashes, persisting entries via UserRepository into MySQL).

📦 Project Structure

src/main/java/com/andrej/auth_api/
│
├── configs/            # Spring Security configuration and dependency beans
│   ├── ApplicationConfiguration.java
│   ├── JwtAuthenticationFilter.java   # Core middleware interceptor
│   └── SecurityConfiguration.java      # Main security filter chain layout
│
├── controllers/        # REST Controllers exposing protected/unprotected routes
│   └── UserController.java
|   └──AuthenticationController.java
│
├── dtos/               # Data Transfer Objects protecting network payloads
│   ├── LoginUserDto.java
│   └── RegisterUserDto.java
│
├── entities/           # Database models mapped via Jakarta Persistence (JPA)
│   └── User.java
│
├── exceptions/         # Global application error safety nets
│   └── GlobalExceptionHandler.java    # Centralized exception translator
│
├── repositories/       # Database access communication interfaces
│   └── UserRepository.java
│
└── services/           # Core business logic orchestrators
    ├── AuthenticationService.java
    └── JwtService.java


🔧 Installation & Setup

Prerequisites

  • Java 17 or higher
  • Maven 3.x
  • MySQL Server (or any alternative relational database)

1. Database Configuration

Create a database in your MySQL instance and update the database connectivity parameters inside src/main/resources/application.properties:

spring.datasource.url=jdbc:mysql://localhost:3606/your_database_name
spring.datasource.username=your_mysql_username
spring.datasource.password=your_mysql_password
spring.jpa.hibernate.ddl-auto=update

2. Run the Application

Navigate to the root directory of the project and execute the following commands in your terminal:

# Clean project and download dependencies
mvn clean install

# Launch the Spring Boot application server
mvn spring-boot:run

The server will boot up and begin listening for incoming requests on http://localhost:8080.


🧪 API Endpoints & Testing (Postman)

1. Public Endpoints (No Token Required)

User Registration

  • HTTP Method: POST
  • URL: http://localhost:8080/auth/signup
  • Payload (JSON):
{
  "email": "user@example.com",
  "password": "securePassword123",
  "fullName": "John Doe"
}

User Login

  • HTTP Method: POST
  • URL: http://localhost:8080/auth/login
  • Payload (JSON):
{
  "email": "user@example.com",
  "password": "securePassword123"
}

Returns a JSON containing the JWT string under the token key.


2. Protected Endpoints (Requires Valid Token)

To access these routes, you must append the JWT token obtained from logging in inside the HTTP Request Header as follows:

  • Key: Authorization
  • Value: Bearer <your_copied_jwt_token>

Get Current Authenticated User Profile

  • HTTP Method: GET
  • URL: http://localhost:8080/users/me

🛡️ License

This project is open-source and available under the MIT License.


About

Implement JWT authentication in a Spring Boot application

Resources

Stars

Watchers

Forks

Releases

Packages

Contributors

Languages