This project demonstrates a simple Role-Based Access Control (RBAC) system built with Spring Boot.
It includes user authentication, registration, and an admin creation endpoint.
Protected routes are secured using JWT tokens and Spring Security.
src/
└─ main/
├─ java/
│ └─ com/
│ └─ rbac/
│ └─ learn/
│ ├─ controller/
│ │ └─ AuthController.java
│ ├─ service/
│ │ └─ AuthService.java
│ ├─ dto/
│ │ └─ AuthRequest.java
│ │ └─ AuthResponse.java
│ │ └─ RegisterRequest.java
│ └─ ...
└─ resources/
└─ application.yml
- Java 17 or higher
- Maven 3.8+
- PostgreSQL (or any JDBC-compatible database)
- Docker (optional, for running the database)
-
Clone the repository
git clone https://github.com/your-username/rbac-project.git cd rbac-project -
Configure the database
Edit
src/main/resources/application.yml:spring: datasource: url: jdbc:postgresql://localhost:5432/rbac_db username: your_user password: your_password jpa: hibernate: ddl-auto: update
Or use Docker:
docker run --name rbac-db -e POSTGRES_DB=rbac_db -e POSTGRES_USER=your_user -e POSTGRES_PASSWORD=your_password -p 5432:5432 postgres
-
Build the project
mvn clean install
-
Run the application
mvn spring-boot:run
The API will be available at
http://localhost:8080/api/auth.
| Method | Endpoint | Description | Access |
|---|---|---|---|
| POST | /api/auth/login |
Authenticate user and receive JWT token | Public |
| POST | /api/auth/register |
Register a new user | Public |
| POST | /api/auth/create-admin |
Create an admin user (requires admin JWT) | Admin |
Register
curl -X POST http://localhost:8080/api/auth/register \
-H "Content-Type: application/json" \
-d '{"username":"john","password":"pass123"}'Login
curl -X POST http://localhost:8080/api/auth/login \
-H "Content-Type: application/json" \
-d '{"username":"john","password":"pass123"}'The response will contain a JWT token:
{
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}Create Admin (requires admin token)
curl -X POST http://localhost:8080/api/auth/create-admin \
-H "Content-Type: application/json" \
-H "Authorization: Bearer <admin-token>" \
-d '{"username":"admin","password":"adminpass"}'All routes under /api/** are secured.
- Public:
/api/auth/login,/api/auth/register - Admin:
/api/auth/create-admin(requiresROLE_ADMIN)
Spring Security is configured to validate the JWT token on each request.
If a request lacks a valid token or the user does not have the required role, a 403 Forbidden response is returned.
Run unit and integration tests with:
mvn testFeel free to open issues or pull requests.
Please follow the existing coding style and add tests for new features.
MIT License