Skip to content

mohammadAlhajeen/spring-multi-user-auth-jwt

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Spring Multi-User Auth & Authorization (Spring Boot + JWT)

A production-ready starter for role-based authentication & authorization using Spring Boot 3, Spring Security 6, and JWT.
Supports multiple roles (e.g. ADMIN, COMPANY, CUSTOMER) with clean layered architecture and REST APIs that are easy to integrate with Web/Mobile clients.

Why use this repo?
Secure login, refresh tokens, role-based access control, and extensible design you can drop into any backend project.


✨ Features

  • JWT Authentication (access + refresh tokens)
  • Role-based Authorization (ADMIN / COMPANY / CUSTOMER)
  • Password hashing (BCrypt)
  • Stateless Security with filters chain
  • Refresh token rotation and revoke on logout
  • Exception handling & error responses (problem details)
  • Validation (Jakarta Validation) & DTO mapping
  • Clean architecture (Controller → Service → Repository)
  • Docker-ready & environment variables support

🧩 Tech Stack

  • Java 17+/21+, Spring Boot 3.x, Spring Security 6
  • JWT (jjwt / java-jwt), Spring Web, Spring Validation
  • JPA/Hibernate, PostgreSQL (or H2 for dev)
  • Lombok, MapStruct (optional), Testcontainers/JUnit (optional)
  • Maven/Gradle

👥 Roles & Permissions (example)

Role Endpoints (examples)
ADMIN /api/admin/** manage users, roles, companies
COMPANY /api/company/** manage products/orders/profile
CUSTOMER /api/customer/** profile, orders, cart
PUBLIC /api/auth/** register/login/refresh

Adjust roles and matchers in SecurityConfig as needed.


🏗️ Architecture

com.example.auth
├─ config/           # SecurityConfig, JWT filters, CORS
├─ auth/             # AuthController, DTOs, AuthService
├─ user/             # User entity, Role enum, repository
├─ common/           # Exceptions, ApiResponse, utils
└─ ...
  • JWTFilter extracts & validates token → builds Authentication
  • Access token short-lived; Refresh token longer-lived, stored/rotated

🔧 Requirements

  • JDK 17+ (or 21/22)
  • PostgreSQL (or H2 for dev)
  • Maven or Gradle

⚙️ Environment Variables

Create .env or use application.yml:

server:
  port: 8080

spring:
  datasource:
    url: jdbc:postgresql://localhost:5432/authdb
    username: postgres
    password: postgres
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: false

security:
  jwt:
    secret: YOUR_SUPER_SECRET_256BIT_KEY
    access-token-exp-min: 15
    refresh-token-exp-days: 7
    issuer: spring-auth

Use a strong 256-bit secret. For prod, load from environment variables.


▶️ Run

Maven

mvn clean spring-boot:run

Gradle

./gradlew bootRun

Docker (example)

docker compose up -d

🔐 Auth Flow (example endpoints)

Register

POST /api/auth/register
{
  "email": "user@example.com",
  "password": "P@ssw0rd!",
  "fullName": "Mohamed Alhajeen",
  "role": "CUSTOMER"   // ADMIN / COMPANY / CUSTOMER
}

Login

POST /api/auth/login
{
  "email": "user@example.com",
  "password": "P@ssw0rd!"
}

→ 200 OK
{
  "accessToken":  "<JWT_ACCESS>",
  "refreshToken": "<JWT_REFRESH>",
  "tokenType": "Bearer",
  "expiresIn": 900
}

Access Protected Resource

GET /api/customer/profile
Authorization: Bearer <JWT_ACCESS>

Refresh Token

POST /api/auth/refresh
{
  "refreshToken": "<JWT_REFRESH>"
}

Logout (invalidate refresh)

POST /api/auth/logout
Authorization: Bearer <JWT_ACCESS>

Configure matchers in SecurityConfig:

.authorizeHttpRequests(auth -> auth
  .requestMatchers("/api/auth/**").permitAll()
  .requestMatchers("/api/admin/**").hasRole("ADMIN")
  .requestMatchers("/api/company/**").hasRole("COMPANY")
  .requestMatchers("/api/customer/**").hasRole("CUSTOMER")
  .anyRequest().authenticated()
)

✅ Testing

  • Use Postman Collection (exported in /postman folder)
  • Or run unit/integration tests:
mvn test
# or
./gradlew test

🖼️ Screenshots

Add images in docs/ and reference them here:

docs/
 ├─ login.png
 ├─ refresh.png
 └─ rbac.png
![Login](docs/login.png)
![Refresh Token](docs/refresh.png)
![RBAC](docs/rbac.png)

📦 Reuse / Extend

  • Add new roles: extend Role enum + authorities mapping
  • Plug into existing project: copy auth, config, user packages and wire beans
  • Swap DB: change datasource + JPA dialect

📜 License

Open-source. Choose MIT/Apache-2.0 and add LICENSE file.


🙌 Credits

Built by Mohamed Alhajeen · Open to collaboration & PRs.
For commercial support or custom features, open an issue or contact me.


(اختياري) وصف عربي مختصر للريبو

مشروع جاهز لتسجيل الدخول والصلاحيات باستخدام Spring Boot وJWT، مع أدوار متعددة (مدير/شركة/زبون) ومعمارية نظيفة قابلة للتوسّع، مناسب للدمج في أي نظام Web أو Mobile.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages