Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

2 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Spring Boot JWT Authentication & RBAC System

A production-ready RESTful API for user authentication and authorization using JWT tokens and role-based access control (RBAC) built with Spring Boot 3, Spring Security 6, and PostgreSQL.

πŸš€ Features

  • βœ… User Registration & Login - Secure user account creation and authentication
  • βœ… JWT Token Authentication - Stateless authentication using JSON Web Tokens
  • βœ… Role-Based Access Control - USER and ADMIN roles with method-level security
  • βœ… Password Hashing - BCrypt password encryption
  • βœ… Token Validation - Automatic JWT validation on protected endpoints
  • βœ… Error Handling - Standardized error responses
  • βœ… API Documentation - Interactive Swagger UI documentation
  • βœ… PostgreSQL Database - Persistent data storage with JPA/Hibernate

πŸ› οΈ Technology Stack

  • Java 17
  • Spring Boot 3.2.1
  • Spring Security 6
  • Spring Data JPA
  • PostgreSQL - Database
  • JSON Web Tokens (JWT) - Authentication
  • Lombok - Boilerplate reduction
  • SpringDoc OpenAPI 3 - API documentation
  • Maven - Build tool

πŸ“‹ Prerequisites

  • Java 17 or higher
  • PostgreSQL 12 or higher
  • Maven 3.6+
  • Git

βš™οΈ Installation & Setup

1. Clone the repository

git clone <repository-url>
cd springboot_Auth_jwt_rbac

2. Configure PostgreSQL Database

Create a PostgreSQL database:

# Using psql
psql -U postgres
CREATE DATABASE spring_auth;
\q

Or using the command line:

createdb -U postgres spring_auth

3. Update Database Configuration (Optional)

Edit src/main/resources/application.properties if you need to change database credentials:

spring.datasource.url=jdbc:postgresql://localhost:5432/spring_auth
spring.datasource.username=postgres
spring.datasource.password=root

4. Build the Project

mvn clean install

5. Run the Application

mvn spring-boot:run

Or run the JAR file:

java -jar target/jwt-auth-rbac-0.0.1-SNAPSHOT.jar

The application will start on http://localhost:8080

πŸ“š API Documentation

Swagger UI

Access the interactive API documentation at:

http://localhost:8080/swagger-ui.html

OpenAPI Specification

Get the OpenAPI JSON specification at:

http://localhost:8080/v3/api-docs

πŸ” API Endpoints

Authentication Endpoints (Public)

Method Endpoint Description
POST /api/auth/register Register a new user
POST /api/auth/login Login user and get JWT token

User Endpoints (Protected)

Method Endpoint Description Required Role
GET /api/users/me Get current user profile USER, ADMIN
GET /api/users Get all users ADMIN
GET /api/users/{id} Get user by ID ADMIN
DELETE /api/users/{id} Delete user ADMIN

πŸ§ͺ Testing the API

1. Register a New User

curl -X POST http://localhost:8080/api/auth/register \
  -H "Content-Type: application/json" \
  -d '{
    "email": "user@example.com",
    "password": "password123",
    "fullName": "John Doe"
  }'

Response:

{
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "email": "user@example.com",
  "fullName": "John Doe",
  "role": "USER",
  "expiresIn": 3600000
}

2. Login

curl -X POST http://localhost:8080/api/auth/login \
  -H "Content-Type: application/json" \
  -d '{
    "email": "user@example.com",mvn spring-boot:run
    "password": "password123"
  }'

3. Access Protected Endpoint

curl -X GET http://localhost:8080/api/users/me \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"

4. Test Without Token (Should Return 401)

curl -X GET http://localhost:8080/api/users/me

πŸ—‚οΈ Project Structure

springboot_Auth_jwt_rbac/
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ main/
β”‚   β”‚   β”œβ”€β”€ java/com/auth/jwt/
β”‚   β”‚   β”‚   β”œβ”€β”€ config/              # Configuration classes
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ ApplicationConfig.java
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ OpenApiConfig.java
β”‚   β”‚   β”‚   β”‚   └── SecurityConfig.java
β”‚   β”‚   β”‚   β”œβ”€β”€ controller/          # REST controllers
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ AuthenticationController.java
β”‚   β”‚   β”‚   β”‚   └── UserController.java
β”‚   β”‚   β”‚   β”œβ”€β”€ dto/                 # Data Transfer Objects
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ AuthResponse.java
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ ErrorResponse.java
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ LoginRequest.java
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ RegisterRequest.java
β”‚   β”‚   β”‚   β”‚   └── UserResponse.java
β”‚   β”‚   β”‚   β”œβ”€β”€ entity/              # JPA entities
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ Role.java
β”‚   β”‚   β”‚   β”‚   └── User.java
β”‚   β”‚   β”‚   β”œβ”€β”€ exception/           # Custom exceptions
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ GlobalExceptionHandler.java
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ InvalidCredentialsException.java
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ ResourceNotFoundException.java
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ UnauthorizedAccessException.java
β”‚   β”‚   β”‚   β”‚   └── UserAlreadyExistsException.java
β”‚   β”‚   β”‚   β”œβ”€β”€ filter/              # Security filters
β”‚   β”‚   β”‚   β”‚   └── JwtAuthenticationFilter.java
β”‚   β”‚   β”‚   β”œβ”€β”€ repository/          # Data repositories
β”‚   β”‚   β”‚   β”‚   └── UserRepository.java
β”‚   β”‚   β”‚   β”œβ”€β”€ security/            # Security utilities
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ CustomUserDetailsService.java
β”‚   β”‚   β”‚   β”‚   └── JwtUtil.java
β”‚   β”‚   β”‚   β”œβ”€β”€ service/             # Business logic
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ AuthenticationService.java
β”‚   β”‚   β”‚   β”‚   └── UserService.java
β”‚   β”‚   β”‚   └── JwtAuthApplication.java
β”‚   β”‚   └── resources/
β”‚   β”‚       └── application.properties
β”‚   └── test/                        # Test files
β”œβ”€β”€ pom.xml
└── README.md

πŸ”’ Security Best Practices

Implemented Security Features

  1. Password Hashing - All passwords are hashed using BCrypt before storage
  2. JWT Token Security - Tokens are signed with a secret key and validated on each request
  3. Token Expiration - Tokens expire after 1 hour (configurable)
  4. Stateless Authentication - No server-side session storage
  5. Role-Based Authorization - Method-level security with @PreAuthorize
  6. Input Validation - Request validation using Bean Validation
  7. Error Security - Sensitive information is not leaked in error messages

Production Recommendations

⚠️ Important: Before deploying to production:

  1. Change JWT Secret - Store in environment variables or secrets manager
  2. Use HTTPS - Enable SSL/TLS for all communications
  3. Database Security - Use strong database passwords and restrict access
  4. Environment Variables - Externalize all sensitive configuration
  5. CORS Configuration - Configure CORS policies for your frontend domain
  6. Rate Limiting - Implement rate limiting to prevent brute force attacks
  7. Logging & Monitoring - Add comprehensive logging and monitoring

🎯 How Authentication Works

  1. Registration/Login β†’ User provides credentials
  2. Password Verification β†’ Password is verified using BCrypt
  3. JWT Generation β†’ Server generates JWT token with user info
  4. Token Response β†’ Token is sent to client
  5. Client Storage β†’ Client stores token (localStorage/sessionStorage)
  6. Protected Requests β†’ Client sends token in Authorization header
  7. Token Validation β†’ Server validates token on each request
  8. Access Granted β†’ User accesses protected resources

πŸ“ Configuration

JWT Configuration

Edit src/main/resources/application.properties:

# JWT secret key (Base64 encoded) - CHANGE IN PRODUCTION!
jwt.secret=404E635266556A586E3272357538782F413F4428472B4B6250645367566B5970

# JWT expiration time in milliseconds (1 hour = 3600000 ms)
jwt.expiration=3600000

Database Configuration

spring.datasource.url=jdbc:postgresql://localhost:5432/todo_db
spring.datasource.username=postgres
spring.datasource.password=root

πŸ§‘β€πŸ’Ό Creating an Admin User

The system assigns the USER role by default. To create an admin user:

  1. Register a new user via API
  2. Manually update the role in the database:
UPDATE users SET role = 'ADMIN' WHERE email = 'admin@example.com';

Or use a database client to manually set the role to ADMIN.

πŸ“Š Database Schema

Users Table

Column Type Constraints
id BIGSERIAL PRIMARY KEY
email VARCHAR(100) UNIQUE, NOT NULL
password VARCHAR(255) NOT NULL
full_name VARCHAR(100) NOT NULL
role VARCHAR(20) NOT NULL
created_at TIMESTAMP NOT NULL
updated_at TIMESTAMP NOT NULL

πŸ› Troubleshooting

Database Connection Issues

Error: Connection refused

Solution: Ensure PostgreSQL is running and credentials are correct.

JWT Token Expired

Error: JWT token has expired

Solution: Login again to get a new token.

Access Denied (403)

Error: Access denied

Solution: Ensure you have the required role (ADMIN) for the endpoint.

πŸ“„ License

This project is licensed under the MIT License.

πŸ‘¨β€πŸ’» Author

Spring Boot JWT Auth Team

🀝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.


Happy Coding! πŸš€

About

The project demonstrates core security concepts such as custom authentication management, Spring Security filters, JWT validation, and secure session handling without server-side state. It is designed following backend best practices and is suitable as a production-ready foundation for modern RESTful applications.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages