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": "[email protected]",
  "password": "SecurePass123",
  "confirmPassword": "SecurePass123",
  "cargo": 1
}

Login

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

Response (Login Success)

{
  "data": {
    "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
    "username": "johndoe",
    "email": "[email protected]",
    "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