Skip to content

H0wZy/jwt-java

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

JWT Authentication API - Spring Boot

A complete authentication API built with Spring Boot, implementing JWT tokens, Repository Pattern, and SOLID principles for secure user management.

πŸš€ Features

  • JWT Authentication - Secure token-based authentication
  • User Registration - Create new user accounts with validation
  • User Login - Authenticate with username or email
  • Protected Endpoints - Secure routes requiring valid JWT tokens
  • Password Security - PBKDF2 hashing with salt for password protection
  • Repository Pattern - Clean data access layer abstraction
  • SOLID Principles - Maintainable and extensible code architecture
  • Input Validation - Comprehensive request data validation
  • Swagger Documentation - Interactive API documentation with JWT support

πŸ› οΈ Technologies Used

  • Java 17 - Latest LTS Java version
  • Spring Boot 3.5.4 - Application framework
  • Spring Security - Authentication and authorization
  • Spring Data JPA - Data persistence
  • JWT (JSON Web Tokens) - Token-based authentication
  • H2 Database - In-memory database for development
  • Maven - Dependency management
  • PBKDF2 - Password hashing algorithm

πŸ“‹ Prerequisites

βš™οΈ Setup & Installation

  1. Clone the repository

    git clone https://github.com/H0wZy/jwt-java.git
    cd jwt-java
  2. Install dependencies

    mvn clean install
  3. Run the application

    mvn spring-boot:run
  4. Access the application

    • API: http://localhost:8080
    • H2 Console: http://localhost:8080/h2-console
    • Swagger UI: http://localhost:8080/swagger-ui.html

πŸ“š API Endpoints

Authentication

Method Endpoint Description Auth Required
POST /api/auth/register Register new user ❌
POST /api/auth/login User login ❌
GET /api/auth/profile Get user profile βœ…

Example Requests

Register User

POST /api/auth/register
{
  "firstname": "John",
  "lastname": "Doe",
  "username": "johndoe",
  "email": "john@example.com",
  "password": "SecurePass123",
  "confirmPassword": "SecurePass123",
  "cargo": 1
}

Login

POST /api/auth/login
{
  "usernameOrEmail": "johndoe",
  "password": "SecurePass123"
}

Response (Login Success)

{
  "data": {
    "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
    "username": "johndoe",
    "email": "john@example.com",
    "firstname": "John",
    "lastname": "Doe",
    "cargo": 1
  },
  "message": "Login successful!",
  "success": true
}

πŸ—οΈ Project Structure

src/main/java/com/example/jwtjava/
β”œβ”€β”€ controller/
β”‚   └── AuthController.java       # Authentication endpoints
β”œβ”€β”€ dto/
β”‚   β”œβ”€β”€ LoginDto.java            # Login request model
β”‚   β”œβ”€β”€ RegisterDto.java         # Registration request model
β”‚   β”œβ”€β”€ LoginResponseDto.java    # Login response model
β”‚   β”œβ”€β”€ RegisterResponseDto.java # Registration response model
β”‚   └── ResponseModelDto.java    # Generic API response wrapper
β”œβ”€β”€ entity/
β”‚   └── User.java                # User entity
β”œβ”€β”€ enums/
β”‚   └── Cargo.java               # User roles enumeration
β”œβ”€β”€ repository/
β”‚   └── UserRepository.java      # User repository interface
β”œβ”€β”€ service/
β”‚   β”œβ”€β”€ AuthService.java         # Authentication service interface
β”‚   └── AuthServiceImpl.java     # Business logic implementation
β”œβ”€β”€ util/
β”‚   β”œβ”€β”€ PasswordHelper.java      # Password hashing utilities
β”‚   └── JwtHelper.java           # JWT token generation
β”œβ”€β”€ config/
β”‚   └── SecurityConfig.java      # Spring Security configuration
└── JwtJavaApplication.java      # Main application class

πŸ” Security Features

  • Password Hashing: PBKDF2 with 100,000 iterations and random salt
  • JWT Tokens: 30-minute expiration with secure claims
  • Input Validation: Comprehensive validation on all endpoints using Bean Validation
  • Authorization: Protected endpoints require valid Bearer tokens

πŸ§ͺ Testing with Swagger

  1. Register a new user using /api/auth/register
  2. Login with the created user via /api/auth/login
  3. Copy the JWT token from the login response
  4. Click "Authorize" button in Swagger UI
  5. Enter: Bearer YOUR_TOKEN_HERE
  6. Test protected endpoints like /api/auth/profile

πŸ”§ Configuration

JWT Settings (application.properties)

# JWT Configuration
jwt.secret=your-secret-key-here-must-be-256-bits-minimum
jwt.expiration=1800000

# Database Configuration (H2 for development)
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=

# JPA Configuration
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.show-sql=true

# H2 Console (for development)
spring.h2.console.enabled=true

πŸ“‹ Current Implementation Status

  • βœ… Enum Cargo - User roles (USER, MOD, ADMIN)
  • βœ… User Entity - User model with validations
  • βœ… DTOs - Transfer objects for requests/responses
  • βœ… PasswordHelper - PBKDF2 password hashing with salt
  • βœ… JwtHelper - JWT token generation and validation

πŸš€ Next Steps / Roadmap

  • Repository Layer - User repository implementation
  • Service Layer - Authentication service
  • Security Configuration - Spring Security setup
  • Authentication Controller - Register and login endpoints
  • JWT Authentication Filter - Token validation middleware
  • Exception Handling - Global exception handler
  • Unit Tests - Comprehensive test coverage
  • Integration Tests - API endpoint testing
  • Docker Support - Containerization
  • Refresh Tokens - Token refresh mechanism
  • Role-based Authorization - Granular permissions
  • Password Reset - Email-based password recovery

🀝 Contributing

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

πŸ“š Original Project

This project is a Java/Spring Boot translation/adaptation of the original C# project:

πŸ“„ License

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

πŸ“ž Contact


⭐ Star this repository if you found it helpful!

About

This project is a study about jwt using Spring Boot & Java

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages