Skip to content

Enterprise-grade loan management system built with Spring Boot 3.x, featuring advanced security mechanisms and complex business logic for real-world financial operations.

Notifications You must be signed in to change notification settings

YasirAkbal/secureloan-api

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

33 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

🏦 SecureLoan API

Enterprise-grade loan management system built with Spring Boot 3.x, featuring advanced security mechanisms and complex business logic for real-world financial operations.


🎯 Project Overview

SecureLoan API implements sophisticated financial workflows including automated credit scoring, debt-to-income (DTI) ratio calculations, annuity-based installment generation, and multi-role authorization with comprehensive audit trails.


🔐 Advanced Security Features

JWT Authentication & Authorization

  • RSA-based JWT with public/private key pair
  • Role-based access control (Customer, Credit Officer, Admin)
  • Method-level security with @PreAuthorize for resource-specific authorization
  • Custom security services for fine-grained access control

Brute-Force Protection

  • Failed login tracking with automatic account locking (5 attempts)
  • Temporary locks (15 minutes) with auto-unlock mechanism
  • Admin locks (permanent until manual intervention)

JWT Blacklist System

  • Token invalidation for logout, password change, and force logout
  • Automatic cleanup of expired tokens (scheduled hourly)
  • Custom filter (JwtBlacklistFilter) validates every request

Refresh Token Security

  • 7-day validity with automatic rotation
  • Reuse detection - if a refresh token is reused, all user tokens are revoked

Custom Security Filter Chain

JwtBlacklistFilter → Token Blacklisted? → Account Locked? → Token Expired? → Allow/Deny

Dual Audit Logging System

1. AOP-Based Security Audit Log

  • Automatic logging of critical operations using @Auditable annotation
  • Tracks: loan approvals, user locks, password changes, force logouts
  • Success/failure tracking with detailed error messages
  • SpEL-based resource extraction for dynamic audit trails

2. Login History Tracking

  • Device fingerprinting (browser, OS, device type)
  • IP address tracking with proxy header support
  • Failed/successful login attempts
  • User-accessible via /api/audit/login-history

💼 Business Logic & Domain

Loan Application Workflow

Auto-Evaluation Engine:

  • Credit score validation (min 500)
  • Age eligibility (max 65 at loan maturity)
  • DTI ratio calculation (max 40% of monthly income)
  • Minimum income requirements per loan type
  • Auto-approval for credit scores ≥750

Loan Types:

  • Personal (1.75% monthly interest, ₺25K min income)
  • Vehicle (1.89% monthly interest, ₺45K min income)
  • Mortgage (1.25% monthly interest, ₺55K min income)
  • Education (1.50% monthly interest, ₺15K min income)

Financial Calculations

Annuity Formula Implementation:

Monthly Installment = P × r × (1+r)^n / ((1+r)^n - 1)
  • Principal tracking with interest separation
  • Last installment adjustment for rounding precision
  • Remaining balance updates on each payment

DTI Calculation:

DTI = (Sum of all active loan installments + new loan installment) / Monthly Income × 100

Installment Payment System

  • Sequential payment enforcement (can't pay installment 3 before installment 2)
  • Already-paid validation
  • Amount matching (exact payment required)
  • Automatic loan completion when all installments paid

🏗️ Project Structure

src/main/java/com/yasirakbal/secureloanapi/
│
├── 📦 common/                    # Shared components
│   ├── entity/BaseEntity        # Auditing fields, soft delete
│   ├── exception/               # Custom exception hierarchy
│   └── mapper/BaseMapper        # MapStruct base interface
│
├── 🔐 security/
│   ├── config/
│   │   ├── SecurityConfig       # Spring Security configuration
│   │   ├── JwtConfig            # JWT encoder/decoder setup
│   │   └── RsaKeysConfig        # Runtime RSA key generation
│   └── filter/
│       └── JwtBlacklistFilter   # Custom pre-authentication filter
│
├── 🎯 feature/
│   │
│   ├── 🔑 auth/                 # Authentication
│   │   ├── adapter/AppUserAdapter
│   │   ├── service/
│   │   │   ├── AuthService      # Login, register, logout
│   │   │   └── RefreshTokenService
│   │   └── entity/RefreshToken
│   │
│   ├── 👤 user/
│   │   ├── entity/User          # Security fields (accountLocked, tokensInvalidatedAt)
│   │   └── service/
│   │       └── UserService      # Password change, failed login handling
│   │
│   ├── 📝 audit/
│   │   ├── aspect/AuditAspect   # AOP-based audit logging
│   │   ├── entity/
│   │   │   ├── SecurityAuditLog
│   │   │   └── LoginHistory
│   │   └── annotation/@Auditable
│   │
│   ├── 🚫 blacklist/
│   │   ├── entity/JwtBlacklist
│   │   └── service/JwtBlacklistService
│   │
│   ├── 📋 application/          # Loan applications
│   │   ├── entity/LoanApplication
│   │   └── service/
│   │       └── LoanApplicationService  # Auto-evaluation, DTI calculation
│   │
│   ├── 💰 loan/
│   │   ├── entity/Loan
│   │   └── service/LoanService  # Payment processing
│   │
│   ├── 📊 installment/
│   │   ├── entity/Installment
│   │   └── service/InstallmentService  # Annuity calculations
│   │
│   ├── 👨‍💼 officer/             # Credit officer operations
│   │   └── service/CreditOfficerService  # Approve/reject loans
│   │
│   └── 👑 admin/
│       └── service/AdminService  # User lock/unlock, force logout
│
└── 🐳 docker-compose.yml        # PostgreSQL container

🚀 Key Technical Highlights

Exception-Driven Design with Transaction Control

@Transactional(
    propagation = Propagation.REQUIRES_NEW,
    noRollbackFor = NonRollbackBusinessException.class
)
  • Throw exceptions while committing database changes
  • Used for failed login tracking (increment attempts but throw error)

AOP-Based Cross-Cutting Concerns

@Aspect
@Component
public class AuditAspect {
    @AfterReturning("@annotation(auditable)")
    public void auditSuccess(JoinPoint joinPoint, Auditable auditable) {
        // Automatic audit logging
    }
}

Scheduled Background Jobs

  • Token cleanup (hourly for blacklist, daily for refresh tokens)
  • Automatic account unlock on login attempt after lock expiry

MapStruct Integration

  • Type-safe DTO mapping
  • Custom conversion logic for complex types
  • Reduces boilerplate code

📡 API Overview

Endpoint Role Description
POST /api/auth/register Public Register new user
POST /api/auth/login Public Login with credentials
POST /api/auth/refresh Public Refresh access token
POST /api/applications Customer Create loan application
GET /api/applications/my Customer View own applications
GET /api/loans/my Customer View active loans
POST /api/loans/{id}/installments/{id}/pay Customer Pay installment
GET /api/officer/applications Officer View pending applications
PUT /api/officer/applications/{id}/approve Officer Approve loan
POST /api/admin/users/{id}/lock Admin Lock user account
GET /api/admin/security/audit-logs Admin View audit logs

🛠️ Tech Stack

  • Spring Boot 3.x - Core framework
  • Spring Security 6 - Authentication & authorization
  • Spring Data JPA - Database operations
  • PostgreSQL - Primary database
  • MapStruct - DTO mapping
  • Argon2 - Password hashing
  • JWT (Nimbus) - Token generation
  • Lombok - Boilerplate reduction
  • Docker - PostgreSQL containerization

⚡ Quick Start

# Start PostgreSQL
docker-compose up -d

# Run application
./mvnw spring-boot:run

Default Users:

  • Customer: johndoe / Pass123!
  • Officer: creditofficer / Pass123!
  • Admin: admin / Pass123!

🎓 What I Learned

This project demonstrates production-grade practices including:

  • Multi-layer security (filters, method-level, custom services)
  • Complex transaction management with propagation strategies
  • AOP for cross-cutting concerns
  • Financial domain modeling
  • Comprehensive error handling with custom exceptions
  • Audit trail implementation for compliance

About

Enterprise-grade loan management system built with Spring Boot 3.x, featuring advanced security mechanisms and complex business logic for real-world financial operations.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages